orztv commited on
Commit
5bab120
1 Parent(s): 27ea706
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .deepsource.toml +7 -0
  2. .dockerignore +21 -0
  3. .gitignore +21 -0
  4. CONTRIBUTING.md +39 -0
  5. Dockerfile +25 -0
  6. LICENSE +661 -0
  7. api/LICENSE +661 -0
  8. api/README.md +22 -0
  9. api/package.json +49 -0
  10. api/src/cobalt.js +27 -0
  11. api/src/config.js +56 -0
  12. api/src/core/api.js +329 -0
  13. api/src/misc/console-text.js +16 -0
  14. api/src/misc/crypto.js +27 -0
  15. api/src/misc/load-from-fs.js +20 -0
  16. api/src/misc/randomize-ciphers.js +28 -0
  17. api/src/misc/run-test.js +44 -0
  18. api/src/misc/utils.js +78 -0
  19. api/src/processing/cookie/cookie.js +37 -0
  20. api/src/processing/cookie/manager.js +66 -0
  21. api/src/processing/create-filename.js +56 -0
  22. api/src/processing/match-action.js +212 -0
  23. api/src/processing/match.js +310 -0
  24. api/src/processing/request.js +97 -0
  25. api/src/processing/schema.js +47 -0
  26. api/src/processing/service-alias.js +10 -0
  27. api/src/processing/service-config.js +182 -0
  28. api/src/processing/service-patterns.js +76 -0
  29. api/src/processing/services/bilibili.js +112 -0
  30. api/src/processing/services/bluesky.js +116 -0
  31. api/src/processing/services/dailymotion.js +107 -0
  32. api/src/processing/services/facebook.js +57 -0
  33. api/src/processing/services/instagram.js +372 -0
  34. api/src/processing/services/loom.js +39 -0
  35. api/src/processing/services/ok.js +65 -0
  36. api/src/processing/services/pinterest.js +46 -0
  37. api/src/processing/services/reddit.js +127 -0
  38. api/src/processing/services/rutube.js +80 -0
  39. api/src/processing/services/snapchat.js +126 -0
  40. api/src/processing/services/soundcloud.js +109 -0
  41. api/src/processing/services/streamable.js +22 -0
  42. api/src/processing/services/tiktok.js +134 -0
  43. api/src/processing/services/tumblr.js +71 -0
  44. api/src/processing/services/twitch.js +90 -0
  45. api/src/processing/services/twitter.js +235 -0
  46. api/src/processing/services/vimeo.js +171 -0
  47. api/src/processing/services/vine.js +15 -0
  48. api/src/processing/services/vk.js +63 -0
  49. api/src/processing/services/youtube.js +313 -0
  50. api/src/processing/url.js +196 -0
.deepsource.toml ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ version = 1
2
+
3
+ [[analyzers]]
4
+ name = "javascript"
5
+
6
+ [analyzers.meta]
7
+ environment = ["nodejs"]
.dockerignore ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # OS directory info files
2
+ .DS_Store
3
+ desktop.ini
4
+
5
+ # node
6
+ node_modules
7
+
8
+ # static build
9
+ build
10
+
11
+ # secrets
12
+ .env
13
+ .env.*
14
+ !.env.example
15
+ cookies.json
16
+
17
+ # docker
18
+ docker-compose.yml
19
+
20
+ # ide
21
+ .vscode
.gitignore ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # OS directory info files
2
+ .DS_Store
3
+ desktop.ini
4
+
5
+ # node
6
+ node_modules
7
+
8
+ # static build
9
+ build
10
+
11
+ # secrets
12
+ .env
13
+ .env.*
14
+ !.env.example
15
+ cookies.json
16
+
17
+ # docker
18
+ docker-compose.yml
19
+
20
+ # ide
21
+ .vscode
CONTRIBUTING.md ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # contributing to cobalt
2
+ if you're reading this, you are probably interested in contributing to cobalt, which we are very thankful for :3
3
+
4
+ this document serves as a guide to help you make contributions that we can merge into the cobalt codebase.
5
+
6
+ ## translations
7
+ currently, we are **not accepting** translations of cobalt. this is because we are making significant changes to the frontend, and the currently used localization structure is being completely reworked. if this changes, this document will be updated.
8
+
9
+ ## adding features or support for services
10
+ before putting in the effort to implement a feature, it's worth considering whether it would be appropriate to add it to cobalt. the cobalt api is built to assist people **only with downloading freely accessible content**. other functionality, such as:
11
+ - downloading paid / not publicly accessible content
12
+ - downloading content protected by DRM
13
+ - scraping unrelated information & exposing it outside of file metadata
14
+
15
+ will not be reviewed or merged.
16
+
17
+ if you plan on adding a feature or support for a service, but are unsure whether it would be appropriate, it's best to open an issue and discuss it beforehand.
18
+
19
+ ## git
20
+ when contributing code to cobalt, there are a few guidelines in place to ensure that the code history is readable and comprehensible.
21
+
22
+ ### clean commit messages
23
+ internally, we use a format similar to [conventional commits](https://www.conventionalcommits.org/en/v1.0.0/) - the first part signifies which part of the code you are changing (the *scope*), and the second part explains the change. for inspiration on how to write appropriate commit titles, you can take a look at the [commit history](https://github.com/imputnet/cobalt/commits/).
24
+
25
+ the scope is not strictly defined, you can write whatever you find most fitting for the particular change. suppose you are changing a small part of a more significant part of the codebase. in that case, you can specify both the larger and smaller scopes in the commit message for clarity (e.g., if you were changing something in internal streams, the commit could be something like `stream/internal: fix object not being handled properly`).
26
+
27
+ if you think a change deserves further explanation, we encourage you to write a short explanation in the commit message ([example](https://github.com/imputnet/cobalt/commit/d2e5b6542f71f3809ba94d56c26f382b5cb62762)), which will save both you and us time having to enquire about the change, and you explaining the reason behind it.
28
+
29
+ if your contribution has uninformative commit titles, you may be asked to interactively rebase your branch and amend each commit to include a meaningful title.
30
+
31
+ ### clean commit history
32
+ if your branch is out of date and/or has some merge conflicts with the `current` branch, you should **rebase** it instead of merging. this prevents meaningless merge commits from being included in your branch, which would then end up in the cobalt git history.
33
+
34
+ if you find a mistake or bug in your code before it's merged or reviewed, instead of making a brand new commit to fix it, it would be preferable to amend that specific commit where the mistake was first introduced. this also helps us easily revert a commit if we discover that it introduced a bug or some unwanted behavior.
35
+ - if the commit you are fixing is the latest one, you can add your files to staging and then use `git commit --amend` to apply the change.
36
+ - if the commit is somewhere deeper in your branch, you can use `git commit --fixup=HASH`, where *`HASH`* is the commit you are fixing.
37
+ - afterward, you must interactively rebase your branch with `git rebase -i current --autosquash`.
38
+ this will open up an editor, but you don't need to do anything else except save the file and exit.
39
+ - once you do either of these things, you will need to do a **force push** to your branch with `git push --force-with-lease`.
Dockerfile ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM node:20-bullseye-slim AS base
2
+ ENV PNPM_HOME="/pnpm"
3
+ ENV PATH="$PNPM_HOME:$PATH"
4
+
5
+ FROM base AS build
6
+ WORKDIR /app
7
+ COPY . /app
8
+
9
+ RUN corepack enable
10
+ RUN apt-get update && \
11
+ apt-get install -y python3 build-essential
12
+
13
+ RUN --mount=type=cache,id=pnpm,target=/pnpm/store \
14
+ pnpm install --prod --frozen-lockfile
15
+
16
+ RUN pnpm deploy --filter=@imput/cobalt-api --prod /prod/api
17
+
18
+ FROM base AS api
19
+ WORKDIR /app
20
+
21
+ COPY --from=build /prod/api /app
22
+ COPY --from=build /app/.git /app/.git
23
+
24
+ EXPOSE 9000
25
+ CMD [ "node", "src/cobalt" ]
LICENSE ADDED
@@ -0,0 +1,661 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ GNU AFFERO GENERAL PUBLIC LICENSE
2
+ Version 3, 19 November 2007
3
+
4
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
5
+ Everyone is permitted to copy and distribute verbatim copies
6
+ of this license document, but changing it is not allowed.
7
+
8
+ Preamble
9
+
10
+ The GNU Affero General Public License is a free, copyleft license for
11
+ software and other kinds of works, specifically designed to ensure
12
+ cooperation with the community in the case of network server software.
13
+
14
+ The licenses for most software and other practical works are designed
15
+ to take away your freedom to share and change the works. By contrast,
16
+ our General Public Licenses are intended to guarantee your freedom to
17
+ share and change all versions of a program--to make sure it remains free
18
+ software for all its users.
19
+
20
+ When we speak of free software, we are referring to freedom, not
21
+ price. Our General Public Licenses are designed to make sure that you
22
+ have the freedom to distribute copies of free software (and charge for
23
+ them if you wish), that you receive source code or can get it if you
24
+ want it, that you can change the software or use pieces of it in new
25
+ free programs, and that you know you can do these things.
26
+
27
+ Developers that use our General Public Licenses protect your rights
28
+ with two steps: (1) assert copyright on the software, and (2) offer
29
+ you this License which gives you legal permission to copy, distribute
30
+ and/or modify the software.
31
+
32
+ A secondary benefit of defending all users' freedom is that
33
+ improvements made in alternate versions of the program, if they
34
+ receive widespread use, become available for other developers to
35
+ incorporate. Many developers of free software are heartened and
36
+ encouraged by the resulting cooperation. However, in the case of
37
+ software used on network servers, this result may fail to come about.
38
+ The GNU General Public License permits making a modified version and
39
+ letting the public access it on a server without ever releasing its
40
+ source code to the public.
41
+
42
+ The GNU Affero General Public License is designed specifically to
43
+ ensure that, in such cases, the modified source code becomes available
44
+ to the community. It requires the operator of a network server to
45
+ provide the source code of the modified version running there to the
46
+ users of that server. Therefore, public use of a modified version, on
47
+ a publicly accessible server, gives the public access to the source
48
+ code of the modified version.
49
+
50
+ An older license, called the Affero General Public License and
51
+ published by Affero, was designed to accomplish similar goals. This is
52
+ a different license, not a version of the Affero GPL, but Affero has
53
+ released a new version of the Affero GPL which permits relicensing under
54
+ this license.
55
+
56
+ The precise terms and conditions for copying, distribution and
57
+ modification follow.
58
+
59
+ TERMS AND CONDITIONS
60
+
61
+ 0. Definitions.
62
+
63
+ "This License" refers to version 3 of the GNU Affero General Public License.
64
+
65
+ "Copyright" also means copyright-like laws that apply to other kinds of
66
+ works, such as semiconductor masks.
67
+
68
+ "The Program" refers to any copyrightable work licensed under this
69
+ License. Each licensee is addressed as "you". "Licensees" and
70
+ "recipients" may be individuals or organizations.
71
+
72
+ To "modify" a work means to copy from or adapt all or part of the work
73
+ in a fashion requiring copyright permission, other than the making of an
74
+ exact copy. The resulting work is called a "modified version" of the
75
+ earlier work or a work "based on" the earlier work.
76
+
77
+ A "covered work" means either the unmodified Program or a work based
78
+ on the Program.
79
+
80
+ To "propagate" a work means to do anything with it that, without
81
+ permission, would make you directly or secondarily liable for
82
+ infringement under applicable copyright law, except executing it on a
83
+ computer or modifying a private copy. Propagation includes copying,
84
+ distribution (with or without modification), making available to the
85
+ public, and in some countries other activities as well.
86
+
87
+ To "convey" a work means any kind of propagation that enables other
88
+ parties to make or receive copies. Mere interaction with a user through
89
+ a computer network, with no transfer of a copy, is not conveying.
90
+
91
+ An interactive user interface displays "Appropriate Legal Notices"
92
+ to the extent that it includes a convenient and prominently visible
93
+ feature that (1) displays an appropriate copyright notice, and (2)
94
+ tells the user that there is no warranty for the work (except to the
95
+ extent that warranties are provided), that licensees may convey the
96
+ work under this License, and how to view a copy of this License. If
97
+ the interface presents a list of user commands or options, such as a
98
+ menu, a prominent item in the list meets this criterion.
99
+
100
+ 1. Source Code.
101
+
102
+ The "source code" for a work means the preferred form of the work
103
+ for making modifications to it. "Object code" means any non-source
104
+ form of a work.
105
+
106
+ A "Standard Interface" means an interface that either is an official
107
+ standard defined by a recognized standards body, or, in the case of
108
+ interfaces specified for a particular programming language, one that
109
+ is widely used among developers working in that language.
110
+
111
+ The "System Libraries" of an executable work include anything, other
112
+ than the work as a whole, that (a) is included in the normal form of
113
+ packaging a Major Component, but which is not part of that Major
114
+ Component, and (b) serves only to enable use of the work with that
115
+ Major Component, or to implement a Standard Interface for which an
116
+ implementation is available to the public in source code form. A
117
+ "Major Component", in this context, means a major essential component
118
+ (kernel, window system, and so on) of the specific operating system
119
+ (if any) on which the executable work runs, or a compiler used to
120
+ produce the work, or an object code interpreter used to run it.
121
+
122
+ The "Corresponding Source" for a work in object code form means all
123
+ the source code needed to generate, install, and (for an executable
124
+ work) run the object code and to modify the work, including scripts to
125
+ control those activities. However, it does not include the work's
126
+ System Libraries, or general-purpose tools or generally available free
127
+ programs which are used unmodified in performing those activities but
128
+ which are not part of the work. For example, Corresponding Source
129
+ includes interface definition files associated with source files for
130
+ the work, and the source code for shared libraries and dynamically
131
+ linked subprograms that the work is specifically designed to require,
132
+ such as by intimate data communication or control flow between those
133
+ subprograms and other parts of the work.
134
+
135
+ The Corresponding Source need not include anything that users
136
+ can regenerate automatically from other parts of the Corresponding
137
+ Source.
138
+
139
+ The Corresponding Source for a work in source code form is that
140
+ same work.
141
+
142
+ 2. Basic Permissions.
143
+
144
+ All rights granted under this License are granted for the term of
145
+ copyright on the Program, and are irrevocable provided the stated
146
+ conditions are met. This License explicitly affirms your unlimited
147
+ permission to run the unmodified Program. The output from running a
148
+ covered work is covered by this License only if the output, given its
149
+ content, constitutes a covered work. This License acknowledges your
150
+ rights of fair use or other equivalent, as provided by copyright law.
151
+
152
+ You may make, run and propagate covered works that you do not
153
+ convey, without conditions so long as your license otherwise remains
154
+ in force. You may convey covered works to others for the sole purpose
155
+ of having them make modifications exclusively for you, or provide you
156
+ with facilities for running those works, provided that you comply with
157
+ the terms of this License in conveying all material for which you do
158
+ not control copyright. Those thus making or running the covered works
159
+ for you must do so exclusively on your behalf, under your direction
160
+ and control, on terms that prohibit them from making any copies of
161
+ your copyrighted material outside their relationship with you.
162
+
163
+ Conveying under any other circumstances is permitted solely under
164
+ the conditions stated below. Sublicensing is not allowed; section 10
165
+ makes it unnecessary.
166
+
167
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
168
+
169
+ No covered work shall be deemed part of an effective technological
170
+ measure under any applicable law fulfilling obligations under article
171
+ 11 of the WIPO copyright treaty adopted on 20 December 1996, or
172
+ similar laws prohibiting or restricting circumvention of such
173
+ measures.
174
+
175
+ When you convey a covered work, you waive any legal power to forbid
176
+ circumvention of technological measures to the extent such circumvention
177
+ is effected by exercising rights under this License with respect to
178
+ the covered work, and you disclaim any intention to limit operation or
179
+ modification of the work as a means of enforcing, against the work's
180
+ users, your or third parties' legal rights to forbid circumvention of
181
+ technological measures.
182
+
183
+ 4. Conveying Verbatim Copies.
184
+
185
+ You may convey verbatim copies of the Program's source code as you
186
+ receive it, in any medium, provided that you conspicuously and
187
+ appropriately publish on each copy an appropriate copyright notice;
188
+ keep intact all notices stating that this License and any
189
+ non-permissive terms added in accord with section 7 apply to the code;
190
+ keep intact all notices of the absence of any warranty; and give all
191
+ recipients a copy of this License along with the Program.
192
+
193
+ You may charge any price or no price for each copy that you convey,
194
+ and you may offer support or warranty protection for a fee.
195
+
196
+ 5. Conveying Modified Source Versions.
197
+
198
+ You may convey a work based on the Program, or the modifications to
199
+ produce it from the Program, in the form of source code under the
200
+ terms of section 4, provided that you also meet all of these conditions:
201
+
202
+ a) The work must carry prominent notices stating that you modified
203
+ it, and giving a relevant date.
204
+
205
+ b) The work must carry prominent notices stating that it is
206
+ released under this License and any conditions added under section
207
+ 7. This requirement modifies the requirement in section 4 to
208
+ "keep intact all notices".
209
+
210
+ c) You must license the entire work, as a whole, under this
211
+ License to anyone who comes into possession of a copy. This
212
+ License will therefore apply, along with any applicable section 7
213
+ additional terms, to the whole of the work, and all its parts,
214
+ regardless of how they are packaged. This License gives no
215
+ permission to license the work in any other way, but it does not
216
+ invalidate such permission if you have separately received it.
217
+
218
+ d) If the work has interactive user interfaces, each must display
219
+ Appropriate Legal Notices; however, if the Program has interactive
220
+ interfaces that do not display Appropriate Legal Notices, your
221
+ work need not make them do so.
222
+
223
+ A compilation of a covered work with other separate and independent
224
+ works, which are not by their nature extensions of the covered work,
225
+ and which are not combined with it such as to form a larger program,
226
+ in or on a volume of a storage or distribution medium, is called an
227
+ "aggregate" if the compilation and its resulting copyright are not
228
+ used to limit the access or legal rights of the compilation's users
229
+ beyond what the individual works permit. Inclusion of a covered work
230
+ in an aggregate does not cause this License to apply to the other
231
+ parts of the aggregate.
232
+
233
+ 6. Conveying Non-Source Forms.
234
+
235
+ You may convey a covered work in object code form under the terms
236
+ of sections 4 and 5, provided that you also convey the
237
+ machine-readable Corresponding Source under the terms of this License,
238
+ in one of these ways:
239
+
240
+ a) Convey the object code in, or embodied in, a physical product
241
+ (including a physical distribution medium), accompanied by the
242
+ Corresponding Source fixed on a durable physical medium
243
+ customarily used for software interchange.
244
+
245
+ b) Convey the object code in, or embodied in, a physical product
246
+ (including a physical distribution medium), accompanied by a
247
+ written offer, valid for at least three years and valid for as
248
+ long as you offer spare parts or customer support for that product
249
+ model, to give anyone who possesses the object code either (1) a
250
+ copy of the Corresponding Source for all the software in the
251
+ product that is covered by this License, on a durable physical
252
+ medium customarily used for software interchange, for a price no
253
+ more than your reasonable cost of physically performing this
254
+ conveying of source, or (2) access to copy the
255
+ Corresponding Source from a network server at no charge.
256
+
257
+ c) Convey individual copies of the object code with a copy of the
258
+ written offer to provide the Corresponding Source. This
259
+ alternative is allowed only occasionally and noncommercially, and
260
+ only if you received the object code with such an offer, in accord
261
+ with subsection 6b.
262
+
263
+ d) Convey the object code by offering access from a designated
264
+ place (gratis or for a charge), and offer equivalent access to the
265
+ Corresponding Source in the same way through the same place at no
266
+ further charge. You need not require recipients to copy the
267
+ Corresponding Source along with the object code. If the place to
268
+ copy the object code is a network server, the Corresponding Source
269
+ may be on a different server (operated by you or a third party)
270
+ that supports equivalent copying facilities, provided you maintain
271
+ clear directions next to the object code saying where to find the
272
+ Corresponding Source. Regardless of what server hosts the
273
+ Corresponding Source, you remain obligated to ensure that it is
274
+ available for as long as needed to satisfy these requirements.
275
+
276
+ e) Convey the object code using peer-to-peer transmission, provided
277
+ you inform other peers where the object code and Corresponding
278
+ Source of the work are being offered to the general public at no
279
+ charge under subsection 6d.
280
+
281
+ A separable portion of the object code, whose source code is excluded
282
+ from the Corresponding Source as a System Library, need not be
283
+ included in conveying the object code work.
284
+
285
+ A "User Product" is either (1) a "consumer product", which means any
286
+ tangible personal property which is normally used for personal, family,
287
+ or household purposes, or (2) anything designed or sold for incorporation
288
+ into a dwelling. In determining whether a product is a consumer product,
289
+ doubtful cases shall be resolved in favor of coverage. For a particular
290
+ product received by a particular user, "normally used" refers to a
291
+ typical or common use of that class of product, regardless of the status
292
+ of the particular user or of the way in which the particular user
293
+ actually uses, or expects or is expected to use, the product. A product
294
+ is a consumer product regardless of whether the product has substantial
295
+ commercial, industrial or non-consumer uses, unless such uses represent
296
+ the only significant mode of use of the product.
297
+
298
+ "Installation Information" for a User Product means any methods,
299
+ procedures, authorization keys, or other information required to install
300
+ and execute modified versions of a covered work in that User Product from
301
+ a modified version of its Corresponding Source. The information must
302
+ suffice to ensure that the continued functioning of the modified object
303
+ code is in no case prevented or interfered with solely because
304
+ modification has been made.
305
+
306
+ If you convey an object code work under this section in, or with, or
307
+ specifically for use in, a User Product, and the conveying occurs as
308
+ part of a transaction in which the right of possession and use of the
309
+ User Product is transferred to the recipient in perpetuity or for a
310
+ fixed term (regardless of how the transaction is characterized), the
311
+ Corresponding Source conveyed under this section must be accompanied
312
+ by the Installation Information. But this requirement does not apply
313
+ if neither you nor any third party retains the ability to install
314
+ modified object code on the User Product (for example, the work has
315
+ been installed in ROM).
316
+
317
+ The requirement to provide Installation Information does not include a
318
+ requirement to continue to provide support service, warranty, or updates
319
+ for a work that has been modified or installed by the recipient, or for
320
+ the User Product in which it has been modified or installed. Access to a
321
+ network may be denied when the modification itself materially and
322
+ adversely affects the operation of the network or violates the rules and
323
+ protocols for communication across the network.
324
+
325
+ Corresponding Source conveyed, and Installation Information provided,
326
+ in accord with this section must be in a format that is publicly
327
+ documented (and with an implementation available to the public in
328
+ source code form), and must require no special password or key for
329
+ unpacking, reading or copying.
330
+
331
+ 7. Additional Terms.
332
+
333
+ "Additional permissions" are terms that supplement the terms of this
334
+ License by making exceptions from one or more of its conditions.
335
+ Additional permissions that are applicable to the entire Program shall
336
+ be treated as though they were included in this License, to the extent
337
+ that they are valid under applicable law. If additional permissions
338
+ apply only to part of the Program, that part may be used separately
339
+ under those permissions, but the entire Program remains governed by
340
+ this License without regard to the additional permissions.
341
+
342
+ When you convey a copy of a covered work, you may at your option
343
+ remove any additional permissions from that copy, or from any part of
344
+ it. (Additional permissions may be written to require their own
345
+ removal in certain cases when you modify the work.) You may place
346
+ additional permissions on material, added by you to a covered work,
347
+ for which you have or can give appropriate copyright permission.
348
+
349
+ Notwithstanding any other provision of this License, for material you
350
+ add to a covered work, you may (if authorized by the copyright holders of
351
+ that material) supplement the terms of this License with terms:
352
+
353
+ a) Disclaiming warranty or limiting liability differently from the
354
+ terms of sections 15 and 16 of this License; or
355
+
356
+ b) Requiring preservation of specified reasonable legal notices or
357
+ author attributions in that material or in the Appropriate Legal
358
+ Notices displayed by works containing it; or
359
+
360
+ c) Prohibiting misrepresentation of the origin of that material, or
361
+ requiring that modified versions of such material be marked in
362
+ reasonable ways as different from the original version; or
363
+
364
+ d) Limiting the use for publicity purposes of names of licensors or
365
+ authors of the material; or
366
+
367
+ e) Declining to grant rights under trademark law for use of some
368
+ trade names, trademarks, or service marks; or
369
+
370
+ f) Requiring indemnification of licensors and authors of that
371
+ material by anyone who conveys the material (or modified versions of
372
+ it) with contractual assumptions of liability to the recipient, for
373
+ any liability that these contractual assumptions directly impose on
374
+ those licensors and authors.
375
+
376
+ All other non-permissive additional terms are considered "further
377
+ restrictions" within the meaning of section 10. If the Program as you
378
+ received it, or any part of it, contains a notice stating that it is
379
+ governed by this License along with a term that is a further
380
+ restriction, you may remove that term. If a license document contains
381
+ a further restriction but permits relicensing or conveying under this
382
+ License, you may add to a covered work material governed by the terms
383
+ of that license document, provided that the further restriction does
384
+ not survive such relicensing or conveying.
385
+
386
+ If you add terms to a covered work in accord with this section, you
387
+ must place, in the relevant source files, a statement of the
388
+ additional terms that apply to those files, or a notice indicating
389
+ where to find the applicable terms.
390
+
391
+ Additional terms, permissive or non-permissive, may be stated in the
392
+ form of a separately written license, or stated as exceptions;
393
+ the above requirements apply either way.
394
+
395
+ 8. Termination.
396
+
397
+ You may not propagate or modify a covered work except as expressly
398
+ provided under this License. Any attempt otherwise to propagate or
399
+ modify it is void, and will automatically terminate your rights under
400
+ this License (including any patent licenses granted under the third
401
+ paragraph of section 11).
402
+
403
+ However, if you cease all violation of this License, then your
404
+ license from a particular copyright holder is reinstated (a)
405
+ provisionally, unless and until the copyright holder explicitly and
406
+ finally terminates your license, and (b) permanently, if the copyright
407
+ holder fails to notify you of the violation by some reasonable means
408
+ prior to 60 days after the cessation.
409
+
410
+ Moreover, your license from a particular copyright holder is
411
+ reinstated permanently if the copyright holder notifies you of the
412
+ violation by some reasonable means, this is the first time you have
413
+ received notice of violation of this License (for any work) from that
414
+ copyright holder, and you cure the violation prior to 30 days after
415
+ your receipt of the notice.
416
+
417
+ Termination of your rights under this section does not terminate the
418
+ licenses of parties who have received copies or rights from you under
419
+ this License. If your rights have been terminated and not permanently
420
+ reinstated, you do not qualify to receive new licenses for the same
421
+ material under section 10.
422
+
423
+ 9. Acceptance Not Required for Having Copies.
424
+
425
+ You are not required to accept this License in order to receive or
426
+ run a copy of the Program. Ancillary propagation of a covered work
427
+ occurring solely as a consequence of using peer-to-peer transmission
428
+ to receive a copy likewise does not require acceptance. However,
429
+ nothing other than this License grants you permission to propagate or
430
+ modify any covered work. These actions infringe copyright if you do
431
+ not accept this License. Therefore, by modifying or propagating a
432
+ covered work, you indicate your acceptance of this License to do so.
433
+
434
+ 10. Automatic Licensing of Downstream Recipients.
435
+
436
+ Each time you convey a covered work, the recipient automatically
437
+ receives a license from the original licensors, to run, modify and
438
+ propagate that work, subject to this License. You are not responsible
439
+ for enforcing compliance by third parties with this License.
440
+
441
+ An "entity transaction" is a transaction transferring control of an
442
+ organization, or substantially all assets of one, or subdividing an
443
+ organization, or merging organizations. If propagation of a covered
444
+ work results from an entity transaction, each party to that
445
+ transaction who receives a copy of the work also receives whatever
446
+ licenses to the work the party's predecessor in interest had or could
447
+ give under the previous paragraph, plus a right to possession of the
448
+ Corresponding Source of the work from the predecessor in interest, if
449
+ the predecessor has it or can get it with reasonable efforts.
450
+
451
+ You may not impose any further restrictions on the exercise of the
452
+ rights granted or affirmed under this License. For example, you may
453
+ not impose a license fee, royalty, or other charge for exercise of
454
+ rights granted under this License, and you may not initiate litigation
455
+ (including a cross-claim or counterclaim in a lawsuit) alleging that
456
+ any patent claim is infringed by making, using, selling, offering for
457
+ sale, or importing the Program or any portion of it.
458
+
459
+ 11. Patents.
460
+
461
+ A "contributor" is a copyright holder who authorizes use under this
462
+ License of the Program or a work on which the Program is based. The
463
+ work thus licensed is called the contributor's "contributor version".
464
+
465
+ A contributor's "essential patent claims" are all patent claims
466
+ owned or controlled by the contributor, whether already acquired or
467
+ hereafter acquired, that would be infringed by some manner, permitted
468
+ by this License, of making, using, or selling its contributor version,
469
+ but do not include claims that would be infringed only as a
470
+ consequence of further modification of the contributor version. For
471
+ purposes of this definition, "control" includes the right to grant
472
+ patent sublicenses in a manner consistent with the requirements of
473
+ this License.
474
+
475
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
476
+ patent license under the contributor's essential patent claims, to
477
+ make, use, sell, offer for sale, import and otherwise run, modify and
478
+ propagate the contents of its contributor version.
479
+
480
+ In the following three paragraphs, a "patent license" is any express
481
+ agreement or commitment, however denominated, not to enforce a patent
482
+ (such as an express permission to practice a patent or covenant not to
483
+ sue for patent infringement). To "grant" such a patent license to a
484
+ party means to make such an agreement or commitment not to enforce a
485
+ patent against the party.
486
+
487
+ If you convey a covered work, knowingly relying on a patent license,
488
+ and the Corresponding Source of the work is not available for anyone
489
+ to copy, free of charge and under the terms of this License, through a
490
+ publicly available network server or other readily accessible means,
491
+ then you must either (1) cause the Corresponding Source to be so
492
+ available, or (2) arrange to deprive yourself of the benefit of the
493
+ patent license for this particular work, or (3) arrange, in a manner
494
+ consistent with the requirements of this License, to extend the patent
495
+ license to downstream recipients. "Knowingly relying" means you have
496
+ actual knowledge that, but for the patent license, your conveying the
497
+ covered work in a country, or your recipient's use of the covered work
498
+ in a country, would infringe one or more identifiable patents in that
499
+ country that you have reason to believe are valid.
500
+
501
+ If, pursuant to or in connection with a single transaction or
502
+ arrangement, you convey, or propagate by procuring conveyance of, a
503
+ covered work, and grant a patent license to some of the parties
504
+ receiving the covered work authorizing them to use, propagate, modify
505
+ or convey a specific copy of the covered work, then the patent license
506
+ you grant is automatically extended to all recipients of the covered
507
+ work and works based on it.
508
+
509
+ A patent license is "discriminatory" if it does not include within
510
+ the scope of its coverage, prohibits the exercise of, or is
511
+ conditioned on the non-exercise of one or more of the rights that are
512
+ specifically granted under this License. You may not convey a covered
513
+ work if you are a party to an arrangement with a third party that is
514
+ in the business of distributing software, under which you make payment
515
+ to the third party based on the extent of your activity of conveying
516
+ the work, and under which the third party grants, to any of the
517
+ parties who would receive the covered work from you, a discriminatory
518
+ patent license (a) in connection with copies of the covered work
519
+ conveyed by you (or copies made from those copies), or (b) primarily
520
+ for and in connection with specific products or compilations that
521
+ contain the covered work, unless you entered into that arrangement,
522
+ or that patent license was granted, prior to 28 March 2007.
523
+
524
+ Nothing in this License shall be construed as excluding or limiting
525
+ any implied license or other defenses to infringement that may
526
+ otherwise be available to you under applicable patent law.
527
+
528
+ 12. No Surrender of Others' Freedom.
529
+
530
+ If conditions are imposed on you (whether by court order, agreement or
531
+ otherwise) that contradict the conditions of this License, they do not
532
+ excuse you from the conditions of this License. If you cannot convey a
533
+ covered work so as to satisfy simultaneously your obligations under this
534
+ License and any other pertinent obligations, then as a consequence you may
535
+ not convey it at all. For example, if you agree to terms that obligate you
536
+ to collect a royalty for further conveying from those to whom you convey
537
+ the Program, the only way you could satisfy both those terms and this
538
+ License would be to refrain entirely from conveying the Program.
539
+
540
+ 13. Remote Network Interaction; Use with the GNU General Public License.
541
+
542
+ Notwithstanding any other provision of this License, if you modify the
543
+ Program, your modified version must prominently offer all users
544
+ interacting with it remotely through a computer network (if your version
545
+ supports such interaction) an opportunity to receive the Corresponding
546
+ Source of your version by providing access to the Corresponding Source
547
+ from a network server at no charge, through some standard or customary
548
+ means of facilitating copying of software. This Corresponding Source
549
+ shall include the Corresponding Source for any work covered by version 3
550
+ of the GNU General Public License that is incorporated pursuant to the
551
+ following paragraph.
552
+
553
+ Notwithstanding any other provision of this License, you have
554
+ permission to link or combine any covered work with a work licensed
555
+ under version 3 of the GNU General Public License into a single
556
+ combined work, and to convey the resulting work. The terms of this
557
+ License will continue to apply to the part which is the covered work,
558
+ but the work with which it is combined will remain governed by version
559
+ 3 of the GNU General Public License.
560
+
561
+ 14. Revised Versions of this License.
562
+
563
+ The Free Software Foundation may publish revised and/or new versions of
564
+ the GNU Affero General Public License from time to time. Such new versions
565
+ will be similar in spirit to the present version, but may differ in detail to
566
+ address new problems or concerns.
567
+
568
+ Each version is given a distinguishing version number. If the
569
+ Program specifies that a certain numbered version of the GNU Affero General
570
+ Public License "or any later version" applies to it, you have the
571
+ option of following the terms and conditions either of that numbered
572
+ version or of any later version published by the Free Software
573
+ Foundation. If the Program does not specify a version number of the
574
+ GNU Affero General Public License, you may choose any version ever published
575
+ by the Free Software Foundation.
576
+
577
+ If the Program specifies that a proxy can decide which future
578
+ versions of the GNU Affero General Public License can be used, that proxy's
579
+ public statement of acceptance of a version permanently authorizes you
580
+ to choose that version for the Program.
581
+
582
+ Later license versions may give you additional or different
583
+ permissions. However, no additional obligations are imposed on any
584
+ author or copyright holder as a result of your choosing to follow a
585
+ later version.
586
+
587
+ 15. Disclaimer of Warranty.
588
+
589
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
590
+ APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
591
+ HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
592
+ OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
593
+ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
594
+ PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
595
+ IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
596
+ ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
597
+
598
+ 16. Limitation of Liability.
599
+
600
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
601
+ WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
602
+ THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
603
+ GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
604
+ USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
605
+ DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
606
+ PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
607
+ EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
608
+ SUCH DAMAGES.
609
+
610
+ 17. Interpretation of Sections 15 and 16.
611
+
612
+ If the disclaimer of warranty and limitation of liability provided
613
+ above cannot be given local legal effect according to their terms,
614
+ reviewing courts shall apply local law that most closely approximates
615
+ an absolute waiver of all civil liability in connection with the
616
+ Program, unless a warranty or assumption of liability accompanies a
617
+ copy of the Program in return for a fee.
618
+
619
+ END OF TERMS AND CONDITIONS
620
+
621
+ How to Apply These Terms to Your New Programs
622
+
623
+ If you develop a new program, and you want it to be of the greatest
624
+ possible use to the public, the best way to achieve this is to make it
625
+ free software which everyone can redistribute and change under these terms.
626
+
627
+ To do so, attach the following notices to the program. It is safest
628
+ to attach them to the start of each source file to most effectively
629
+ state the exclusion of warranty; and each file should have at least
630
+ the "copyright" line and a pointer to where the full notice is found.
631
+
632
+ save what you love with cobalt.
633
+ Copyright (C) 2024 imput
634
+
635
+ This program is free software: you can redistribute it and/or modify
636
+ it under the terms of the GNU Affero General Public License as published by
637
+ the Free Software Foundation, either version 3 of the License, or
638
+ (at your option) any later version.
639
+
640
+ This program is distributed in the hope that it will be useful,
641
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
642
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
643
+ GNU Affero General Public License for more details.
644
+
645
+ You should have received a copy of the GNU Affero General Public License
646
+ along with this program. If not, see <https://www.gnu.org/licenses/>.
647
+
648
+ Also add information on how to contact you by electronic and paper mail.
649
+
650
+ If your software can interact with users remotely through a computer
651
+ network, you should also make sure that it provides a way for users to
652
+ get its source. For example, if your program is a web application, its
653
+ interface could display a "Source" link that leads users to an archive
654
+ of the code. There are many ways you could offer source, and different
655
+ solutions will be better for different programs; see section 13 for the
656
+ specific requirements.
657
+
658
+ You should also get your employer (if you work as a programmer) or school,
659
+ if any, to sign a "copyright disclaimer" for the program, if necessary.
660
+ For more information on this, and how to apply and follow the GNU AGPL, see
661
+ <https://www.gnu.org/licenses/>.
api/LICENSE ADDED
@@ -0,0 +1,661 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ GNU AFFERO GENERAL PUBLIC LICENSE
2
+ Version 3, 19 November 2007
3
+
4
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
5
+ Everyone is permitted to copy and distribute verbatim copies
6
+ of this license document, but changing it is not allowed.
7
+
8
+ Preamble
9
+
10
+ The GNU Affero General Public License is a free, copyleft license for
11
+ software and other kinds of works, specifically designed to ensure
12
+ cooperation with the community in the case of network server software.
13
+
14
+ The licenses for most software and other practical works are designed
15
+ to take away your freedom to share and change the works. By contrast,
16
+ our General Public Licenses are intended to guarantee your freedom to
17
+ share and change all versions of a program--to make sure it remains free
18
+ software for all its users.
19
+
20
+ When we speak of free software, we are referring to freedom, not
21
+ price. Our General Public Licenses are designed to make sure that you
22
+ have the freedom to distribute copies of free software (and charge for
23
+ them if you wish), that you receive source code or can get it if you
24
+ want it, that you can change the software or use pieces of it in new
25
+ free programs, and that you know you can do these things.
26
+
27
+ Developers that use our General Public Licenses protect your rights
28
+ with two steps: (1) assert copyright on the software, and (2) offer
29
+ you this License which gives you legal permission to copy, distribute
30
+ and/or modify the software.
31
+
32
+ A secondary benefit of defending all users' freedom is that
33
+ improvements made in alternate versions of the program, if they
34
+ receive widespread use, become available for other developers to
35
+ incorporate. Many developers of free software are heartened and
36
+ encouraged by the resulting cooperation. However, in the case of
37
+ software used on network servers, this result may fail to come about.
38
+ The GNU General Public License permits making a modified version and
39
+ letting the public access it on a server without ever releasing its
40
+ source code to the public.
41
+
42
+ The GNU Affero General Public License is designed specifically to
43
+ ensure that, in such cases, the modified source code becomes available
44
+ to the community. It requires the operator of a network server to
45
+ provide the source code of the modified version running there to the
46
+ users of that server. Therefore, public use of a modified version, on
47
+ a publicly accessible server, gives the public access to the source
48
+ code of the modified version.
49
+
50
+ An older license, called the Affero General Public License and
51
+ published by Affero, was designed to accomplish similar goals. This is
52
+ a different license, not a version of the Affero GPL, but Affero has
53
+ released a new version of the Affero GPL which permits relicensing under
54
+ this license.
55
+
56
+ The precise terms and conditions for copying, distribution and
57
+ modification follow.
58
+
59
+ TERMS AND CONDITIONS
60
+
61
+ 0. Definitions.
62
+
63
+ "This License" refers to version 3 of the GNU Affero General Public License.
64
+
65
+ "Copyright" also means copyright-like laws that apply to other kinds of
66
+ works, such as semiconductor masks.
67
+
68
+ "The Program" refers to any copyrightable work licensed under this
69
+ License. Each licensee is addressed as "you". "Licensees" and
70
+ "recipients" may be individuals or organizations.
71
+
72
+ To "modify" a work means to copy from or adapt all or part of the work
73
+ in a fashion requiring copyright permission, other than the making of an
74
+ exact copy. The resulting work is called a "modified version" of the
75
+ earlier work or a work "based on" the earlier work.
76
+
77
+ A "covered work" means either the unmodified Program or a work based
78
+ on the Program.
79
+
80
+ To "propagate" a work means to do anything with it that, without
81
+ permission, would make you directly or secondarily liable for
82
+ infringement under applicable copyright law, except executing it on a
83
+ computer or modifying a private copy. Propagation includes copying,
84
+ distribution (with or without modification), making available to the
85
+ public, and in some countries other activities as well.
86
+
87
+ To "convey" a work means any kind of propagation that enables other
88
+ parties to make or receive copies. Mere interaction with a user through
89
+ a computer network, with no transfer of a copy, is not conveying.
90
+
91
+ An interactive user interface displays "Appropriate Legal Notices"
92
+ to the extent that it includes a convenient and prominently visible
93
+ feature that (1) displays an appropriate copyright notice, and (2)
94
+ tells the user that there is no warranty for the work (except to the
95
+ extent that warranties are provided), that licensees may convey the
96
+ work under this License, and how to view a copy of this License. If
97
+ the interface presents a list of user commands or options, such as a
98
+ menu, a prominent item in the list meets this criterion.
99
+
100
+ 1. Source Code.
101
+
102
+ The "source code" for a work means the preferred form of the work
103
+ for making modifications to it. "Object code" means any non-source
104
+ form of a work.
105
+
106
+ A "Standard Interface" means an interface that either is an official
107
+ standard defined by a recognized standards body, or, in the case of
108
+ interfaces specified for a particular programming language, one that
109
+ is widely used among developers working in that language.
110
+
111
+ The "System Libraries" of an executable work include anything, other
112
+ than the work as a whole, that (a) is included in the normal form of
113
+ packaging a Major Component, but which is not part of that Major
114
+ Component, and (b) serves only to enable use of the work with that
115
+ Major Component, or to implement a Standard Interface for which an
116
+ implementation is available to the public in source code form. A
117
+ "Major Component", in this context, means a major essential component
118
+ (kernel, window system, and so on) of the specific operating system
119
+ (if any) on which the executable work runs, or a compiler used to
120
+ produce the work, or an object code interpreter used to run it.
121
+
122
+ The "Corresponding Source" for a work in object code form means all
123
+ the source code needed to generate, install, and (for an executable
124
+ work) run the object code and to modify the work, including scripts to
125
+ control those activities. However, it does not include the work's
126
+ System Libraries, or general-purpose tools or generally available free
127
+ programs which are used unmodified in performing those activities but
128
+ which are not part of the work. For example, Corresponding Source
129
+ includes interface definition files associated with source files for
130
+ the work, and the source code for shared libraries and dynamically
131
+ linked subprograms that the work is specifically designed to require,
132
+ such as by intimate data communication or control flow between those
133
+ subprograms and other parts of the work.
134
+
135
+ The Corresponding Source need not include anything that users
136
+ can regenerate automatically from other parts of the Corresponding
137
+ Source.
138
+
139
+ The Corresponding Source for a work in source code form is that
140
+ same work.
141
+
142
+ 2. Basic Permissions.
143
+
144
+ All rights granted under this License are granted for the term of
145
+ copyright on the Program, and are irrevocable provided the stated
146
+ conditions are met. This License explicitly affirms your unlimited
147
+ permission to run the unmodified Program. The output from running a
148
+ covered work is covered by this License only if the output, given its
149
+ content, constitutes a covered work. This License acknowledges your
150
+ rights of fair use or other equivalent, as provided by copyright law.
151
+
152
+ You may make, run and propagate covered works that you do not
153
+ convey, without conditions so long as your license otherwise remains
154
+ in force. You may convey covered works to others for the sole purpose
155
+ of having them make modifications exclusively for you, or provide you
156
+ with facilities for running those works, provided that you comply with
157
+ the terms of this License in conveying all material for which you do
158
+ not control copyright. Those thus making or running the covered works
159
+ for you must do so exclusively on your behalf, under your direction
160
+ and control, on terms that prohibit them from making any copies of
161
+ your copyrighted material outside their relationship with you.
162
+
163
+ Conveying under any other circumstances is permitted solely under
164
+ the conditions stated below. Sublicensing is not allowed; section 10
165
+ makes it unnecessary.
166
+
167
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
168
+
169
+ No covered work shall be deemed part of an effective technological
170
+ measure under any applicable law fulfilling obligations under article
171
+ 11 of the WIPO copyright treaty adopted on 20 December 1996, or
172
+ similar laws prohibiting or restricting circumvention of such
173
+ measures.
174
+
175
+ When you convey a covered work, you waive any legal power to forbid
176
+ circumvention of technological measures to the extent such circumvention
177
+ is effected by exercising rights under this License with respect to
178
+ the covered work, and you disclaim any intention to limit operation or
179
+ modification of the work as a means of enforcing, against the work's
180
+ users, your or third parties' legal rights to forbid circumvention of
181
+ technological measures.
182
+
183
+ 4. Conveying Verbatim Copies.
184
+
185
+ You may convey verbatim copies of the Program's source code as you
186
+ receive it, in any medium, provided that you conspicuously and
187
+ appropriately publish on each copy an appropriate copyright notice;
188
+ keep intact all notices stating that this License and any
189
+ non-permissive terms added in accord with section 7 apply to the code;
190
+ keep intact all notices of the absence of any warranty; and give all
191
+ recipients a copy of this License along with the Program.
192
+
193
+ You may charge any price or no price for each copy that you convey,
194
+ and you may offer support or warranty protection for a fee.
195
+
196
+ 5. Conveying Modified Source Versions.
197
+
198
+ You may convey a work based on the Program, or the modifications to
199
+ produce it from the Program, in the form of source code under the
200
+ terms of section 4, provided that you also meet all of these conditions:
201
+
202
+ a) The work must carry prominent notices stating that you modified
203
+ it, and giving a relevant date.
204
+
205
+ b) The work must carry prominent notices stating that it is
206
+ released under this License and any conditions added under section
207
+ 7. This requirement modifies the requirement in section 4 to
208
+ "keep intact all notices".
209
+
210
+ c) You must license the entire work, as a whole, under this
211
+ License to anyone who comes into possession of a copy. This
212
+ License will therefore apply, along with any applicable section 7
213
+ additional terms, to the whole of the work, and all its parts,
214
+ regardless of how they are packaged. This License gives no
215
+ permission to license the work in any other way, but it does not
216
+ invalidate such permission if you have separately received it.
217
+
218
+ d) If the work has interactive user interfaces, each must display
219
+ Appropriate Legal Notices; however, if the Program has interactive
220
+ interfaces that do not display Appropriate Legal Notices, your
221
+ work need not make them do so.
222
+
223
+ A compilation of a covered work with other separate and independent
224
+ works, which are not by their nature extensions of the covered work,
225
+ and which are not combined with it such as to form a larger program,
226
+ in or on a volume of a storage or distribution medium, is called an
227
+ "aggregate" if the compilation and its resulting copyright are not
228
+ used to limit the access or legal rights of the compilation's users
229
+ beyond what the individual works permit. Inclusion of a covered work
230
+ in an aggregate does not cause this License to apply to the other
231
+ parts of the aggregate.
232
+
233
+ 6. Conveying Non-Source Forms.
234
+
235
+ You may convey a covered work in object code form under the terms
236
+ of sections 4 and 5, provided that you also convey the
237
+ machine-readable Corresponding Source under the terms of this License,
238
+ in one of these ways:
239
+
240
+ a) Convey the object code in, or embodied in, a physical product
241
+ (including a physical distribution medium), accompanied by the
242
+ Corresponding Source fixed on a durable physical medium
243
+ customarily used for software interchange.
244
+
245
+ b) Convey the object code in, or embodied in, a physical product
246
+ (including a physical distribution medium), accompanied by a
247
+ written offer, valid for at least three years and valid for as
248
+ long as you offer spare parts or customer support for that product
249
+ model, to give anyone who possesses the object code either (1) a
250
+ copy of the Corresponding Source for all the software in the
251
+ product that is covered by this License, on a durable physical
252
+ medium customarily used for software interchange, for a price no
253
+ more than your reasonable cost of physically performing this
254
+ conveying of source, or (2) access to copy the
255
+ Corresponding Source from a network server at no charge.
256
+
257
+ c) Convey individual copies of the object code with a copy of the
258
+ written offer to provide the Corresponding Source. This
259
+ alternative is allowed only occasionally and noncommercially, and
260
+ only if you received the object code with such an offer, in accord
261
+ with subsection 6b.
262
+
263
+ d) Convey the object code by offering access from a designated
264
+ place (gratis or for a charge), and offer equivalent access to the
265
+ Corresponding Source in the same way through the same place at no
266
+ further charge. You need not require recipients to copy the
267
+ Corresponding Source along with the object code. If the place to
268
+ copy the object code is a network server, the Corresponding Source
269
+ may be on a different server (operated by you or a third party)
270
+ that supports equivalent copying facilities, provided you maintain
271
+ clear directions next to the object code saying where to find the
272
+ Corresponding Source. Regardless of what server hosts the
273
+ Corresponding Source, you remain obligated to ensure that it is
274
+ available for as long as needed to satisfy these requirements.
275
+
276
+ e) Convey the object code using peer-to-peer transmission, provided
277
+ you inform other peers where the object code and Corresponding
278
+ Source of the work are being offered to the general public at no
279
+ charge under subsection 6d.
280
+
281
+ A separable portion of the object code, whose source code is excluded
282
+ from the Corresponding Source as a System Library, need not be
283
+ included in conveying the object code work.
284
+
285
+ A "User Product" is either (1) a "consumer product", which means any
286
+ tangible personal property which is normally used for personal, family,
287
+ or household purposes, or (2) anything designed or sold for incorporation
288
+ into a dwelling. In determining whether a product is a consumer product,
289
+ doubtful cases shall be resolved in favor of coverage. For a particular
290
+ product received by a particular user, "normally used" refers to a
291
+ typical or common use of that class of product, regardless of the status
292
+ of the particular user or of the way in which the particular user
293
+ actually uses, or expects or is expected to use, the product. A product
294
+ is a consumer product regardless of whether the product has substantial
295
+ commercial, industrial or non-consumer uses, unless such uses represent
296
+ the only significant mode of use of the product.
297
+
298
+ "Installation Information" for a User Product means any methods,
299
+ procedures, authorization keys, or other information required to install
300
+ and execute modified versions of a covered work in that User Product from
301
+ a modified version of its Corresponding Source. The information must
302
+ suffice to ensure that the continued functioning of the modified object
303
+ code is in no case prevented or interfered with solely because
304
+ modification has been made.
305
+
306
+ If you convey an object code work under this section in, or with, or
307
+ specifically for use in, a User Product, and the conveying occurs as
308
+ part of a transaction in which the right of possession and use of the
309
+ User Product is transferred to the recipient in perpetuity or for a
310
+ fixed term (regardless of how the transaction is characterized), the
311
+ Corresponding Source conveyed under this section must be accompanied
312
+ by the Installation Information. But this requirement does not apply
313
+ if neither you nor any third party retains the ability to install
314
+ modified object code on the User Product (for example, the work has
315
+ been installed in ROM).
316
+
317
+ The requirement to provide Installation Information does not include a
318
+ requirement to continue to provide support service, warranty, or updates
319
+ for a work that has been modified or installed by the recipient, or for
320
+ the User Product in which it has been modified or installed. Access to a
321
+ network may be denied when the modification itself materially and
322
+ adversely affects the operation of the network or violates the rules and
323
+ protocols for communication across the network.
324
+
325
+ Corresponding Source conveyed, and Installation Information provided,
326
+ in accord with this section must be in a format that is publicly
327
+ documented (and with an implementation available to the public in
328
+ source code form), and must require no special password or key for
329
+ unpacking, reading or copying.
330
+
331
+ 7. Additional Terms.
332
+
333
+ "Additional permissions" are terms that supplement the terms of this
334
+ License by making exceptions from one or more of its conditions.
335
+ Additional permissions that are applicable to the entire Program shall
336
+ be treated as though they were included in this License, to the extent
337
+ that they are valid under applicable law. If additional permissions
338
+ apply only to part of the Program, that part may be used separately
339
+ under those permissions, but the entire Program remains governed by
340
+ this License without regard to the additional permissions.
341
+
342
+ When you convey a copy of a covered work, you may at your option
343
+ remove any additional permissions from that copy, or from any part of
344
+ it. (Additional permissions may be written to require their own
345
+ removal in certain cases when you modify the work.) You may place
346
+ additional permissions on material, added by you to a covered work,
347
+ for which you have or can give appropriate copyright permission.
348
+
349
+ Notwithstanding any other provision of this License, for material you
350
+ add to a covered work, you may (if authorized by the copyright holders of
351
+ that material) supplement the terms of this License with terms:
352
+
353
+ a) Disclaiming warranty or limiting liability differently from the
354
+ terms of sections 15 and 16 of this License; or
355
+
356
+ b) Requiring preservation of specified reasonable legal notices or
357
+ author attributions in that material or in the Appropriate Legal
358
+ Notices displayed by works containing it; or
359
+
360
+ c) Prohibiting misrepresentation of the origin of that material, or
361
+ requiring that modified versions of such material be marked in
362
+ reasonable ways as different from the original version; or
363
+
364
+ d) Limiting the use for publicity purposes of names of licensors or
365
+ authors of the material; or
366
+
367
+ e) Declining to grant rights under trademark law for use of some
368
+ trade names, trademarks, or service marks; or
369
+
370
+ f) Requiring indemnification of licensors and authors of that
371
+ material by anyone who conveys the material (or modified versions of
372
+ it) with contractual assumptions of liability to the recipient, for
373
+ any liability that these contractual assumptions directly impose on
374
+ those licensors and authors.
375
+
376
+ All other non-permissive additional terms are considered "further
377
+ restrictions" within the meaning of section 10. If the Program as you
378
+ received it, or any part of it, contains a notice stating that it is
379
+ governed by this License along with a term that is a further
380
+ restriction, you may remove that term. If a license document contains
381
+ a further restriction but permits relicensing or conveying under this
382
+ License, you may add to a covered work material governed by the terms
383
+ of that license document, provided that the further restriction does
384
+ not survive such relicensing or conveying.
385
+
386
+ If you add terms to a covered work in accord with this section, you
387
+ must place, in the relevant source files, a statement of the
388
+ additional terms that apply to those files, or a notice indicating
389
+ where to find the applicable terms.
390
+
391
+ Additional terms, permissive or non-permissive, may be stated in the
392
+ form of a separately written license, or stated as exceptions;
393
+ the above requirements apply either way.
394
+
395
+ 8. Termination.
396
+
397
+ You may not propagate or modify a covered work except as expressly
398
+ provided under this License. Any attempt otherwise to propagate or
399
+ modify it is void, and will automatically terminate your rights under
400
+ this License (including any patent licenses granted under the third
401
+ paragraph of section 11).
402
+
403
+ However, if you cease all violation of this License, then your
404
+ license from a particular copyright holder is reinstated (a)
405
+ provisionally, unless and until the copyright holder explicitly and
406
+ finally terminates your license, and (b) permanently, if the copyright
407
+ holder fails to notify you of the violation by some reasonable means
408
+ prior to 60 days after the cessation.
409
+
410
+ Moreover, your license from a particular copyright holder is
411
+ reinstated permanently if the copyright holder notifies you of the
412
+ violation by some reasonable means, this is the first time you have
413
+ received notice of violation of this License (for any work) from that
414
+ copyright holder, and you cure the violation prior to 30 days after
415
+ your receipt of the notice.
416
+
417
+ Termination of your rights under this section does not terminate the
418
+ licenses of parties who have received copies or rights from you under
419
+ this License. If your rights have been terminated and not permanently
420
+ reinstated, you do not qualify to receive new licenses for the same
421
+ material under section 10.
422
+
423
+ 9. Acceptance Not Required for Having Copies.
424
+
425
+ You are not required to accept this License in order to receive or
426
+ run a copy of the Program. Ancillary propagation of a covered work
427
+ occurring solely as a consequence of using peer-to-peer transmission
428
+ to receive a copy likewise does not require acceptance. However,
429
+ nothing other than this License grants you permission to propagate or
430
+ modify any covered work. These actions infringe copyright if you do
431
+ not accept this License. Therefore, by modifying or propagating a
432
+ covered work, you indicate your acceptance of this License to do so.
433
+
434
+ 10. Automatic Licensing of Downstream Recipients.
435
+
436
+ Each time you convey a covered work, the recipient automatically
437
+ receives a license from the original licensors, to run, modify and
438
+ propagate that work, subject to this License. You are not responsible
439
+ for enforcing compliance by third parties with this License.
440
+
441
+ An "entity transaction" is a transaction transferring control of an
442
+ organization, or substantially all assets of one, or subdividing an
443
+ organization, or merging organizations. If propagation of a covered
444
+ work results from an entity transaction, each party to that
445
+ transaction who receives a copy of the work also receives whatever
446
+ licenses to the work the party's predecessor in interest had or could
447
+ give under the previous paragraph, plus a right to possession of the
448
+ Corresponding Source of the work from the predecessor in interest, if
449
+ the predecessor has it or can get it with reasonable efforts.
450
+
451
+ You may not impose any further restrictions on the exercise of the
452
+ rights granted or affirmed under this License. For example, you may
453
+ not impose a license fee, royalty, or other charge for exercise of
454
+ rights granted under this License, and you may not initiate litigation
455
+ (including a cross-claim or counterclaim in a lawsuit) alleging that
456
+ any patent claim is infringed by making, using, selling, offering for
457
+ sale, or importing the Program or any portion of it.
458
+
459
+ 11. Patents.
460
+
461
+ A "contributor" is a copyright holder who authorizes use under this
462
+ License of the Program or a work on which the Program is based. The
463
+ work thus licensed is called the contributor's "contributor version".
464
+
465
+ A contributor's "essential patent claims" are all patent claims
466
+ owned or controlled by the contributor, whether already acquired or
467
+ hereafter acquired, that would be infringed by some manner, permitted
468
+ by this License, of making, using, or selling its contributor version,
469
+ but do not include claims that would be infringed only as a
470
+ consequence of further modification of the contributor version. For
471
+ purposes of this definition, "control" includes the right to grant
472
+ patent sublicenses in a manner consistent with the requirements of
473
+ this License.
474
+
475
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
476
+ patent license under the contributor's essential patent claims, to
477
+ make, use, sell, offer for sale, import and otherwise run, modify and
478
+ propagate the contents of its contributor version.
479
+
480
+ In the following three paragraphs, a "patent license" is any express
481
+ agreement or commitment, however denominated, not to enforce a patent
482
+ (such as an express permission to practice a patent or covenant not to
483
+ sue for patent infringement). To "grant" such a patent license to a
484
+ party means to make such an agreement or commitment not to enforce a
485
+ patent against the party.
486
+
487
+ If you convey a covered work, knowingly relying on a patent license,
488
+ and the Corresponding Source of the work is not available for anyone
489
+ to copy, free of charge and under the terms of this License, through a
490
+ publicly available network server or other readily accessible means,
491
+ then you must either (1) cause the Corresponding Source to be so
492
+ available, or (2) arrange to deprive yourself of the benefit of the
493
+ patent license for this particular work, or (3) arrange, in a manner
494
+ consistent with the requirements of this License, to extend the patent
495
+ license to downstream recipients. "Knowingly relying" means you have
496
+ actual knowledge that, but for the patent license, your conveying the
497
+ covered work in a country, or your recipient's use of the covered work
498
+ in a country, would infringe one or more identifiable patents in that
499
+ country that you have reason to believe are valid.
500
+
501
+ If, pursuant to or in connection with a single transaction or
502
+ arrangement, you convey, or propagate by procuring conveyance of, a
503
+ covered work, and grant a patent license to some of the parties
504
+ receiving the covered work authorizing them to use, propagate, modify
505
+ or convey a specific copy of the covered work, then the patent license
506
+ you grant is automatically extended to all recipients of the covered
507
+ work and works based on it.
508
+
509
+ A patent license is "discriminatory" if it does not include within
510
+ the scope of its coverage, prohibits the exercise of, or is
511
+ conditioned on the non-exercise of one or more of the rights that are
512
+ specifically granted under this License. You may not convey a covered
513
+ work if you are a party to an arrangement with a third party that is
514
+ in the business of distributing software, under which you make payment
515
+ to the third party based on the extent of your activity of conveying
516
+ the work, and under which the third party grants, to any of the
517
+ parties who would receive the covered work from you, a discriminatory
518
+ patent license (a) in connection with copies of the covered work
519
+ conveyed by you (or copies made from those copies), or (b) primarily
520
+ for and in connection with specific products or compilations that
521
+ contain the covered work, unless you entered into that arrangement,
522
+ or that patent license was granted, prior to 28 March 2007.
523
+
524
+ Nothing in this License shall be construed as excluding or limiting
525
+ any implied license or other defenses to infringement that may
526
+ otherwise be available to you under applicable patent law.
527
+
528
+ 12. No Surrender of Others' Freedom.
529
+
530
+ If conditions are imposed on you (whether by court order, agreement or
531
+ otherwise) that contradict the conditions of this License, they do not
532
+ excuse you from the conditions of this License. If you cannot convey a
533
+ covered work so as to satisfy simultaneously your obligations under this
534
+ License and any other pertinent obligations, then as a consequence you may
535
+ not convey it at all. For example, if you agree to terms that obligate you
536
+ to collect a royalty for further conveying from those to whom you convey
537
+ the Program, the only way you could satisfy both those terms and this
538
+ License would be to refrain entirely from conveying the Program.
539
+
540
+ 13. Remote Network Interaction; Use with the GNU General Public License.
541
+
542
+ Notwithstanding any other provision of this License, if you modify the
543
+ Program, your modified version must prominently offer all users
544
+ interacting with it remotely through a computer network (if your version
545
+ supports such interaction) an opportunity to receive the Corresponding
546
+ Source of your version by providing access to the Corresponding Source
547
+ from a network server at no charge, through some standard or customary
548
+ means of facilitating copying of software. This Corresponding Source
549
+ shall include the Corresponding Source for any work covered by version 3
550
+ of the GNU General Public License that is incorporated pursuant to the
551
+ following paragraph.
552
+
553
+ Notwithstanding any other provision of this License, you have
554
+ permission to link or combine any covered work with a work licensed
555
+ under version 3 of the GNU General Public License into a single
556
+ combined work, and to convey the resulting work. The terms of this
557
+ License will continue to apply to the part which is the covered work,
558
+ but the work with which it is combined will remain governed by version
559
+ 3 of the GNU General Public License.
560
+
561
+ 14. Revised Versions of this License.
562
+
563
+ The Free Software Foundation may publish revised and/or new versions of
564
+ the GNU Affero General Public License from time to time. Such new versions
565
+ will be similar in spirit to the present version, but may differ in detail to
566
+ address new problems or concerns.
567
+
568
+ Each version is given a distinguishing version number. If the
569
+ Program specifies that a certain numbered version of the GNU Affero General
570
+ Public License "or any later version" applies to it, you have the
571
+ option of following the terms and conditions either of that numbered
572
+ version or of any later version published by the Free Software
573
+ Foundation. If the Program does not specify a version number of the
574
+ GNU Affero General Public License, you may choose any version ever published
575
+ by the Free Software Foundation.
576
+
577
+ If the Program specifies that a proxy can decide which future
578
+ versions of the GNU Affero General Public License can be used, that proxy's
579
+ public statement of acceptance of a version permanently authorizes you
580
+ to choose that version for the Program.
581
+
582
+ Later license versions may give you additional or different
583
+ permissions. However, no additional obligations are imposed on any
584
+ author or copyright holder as a result of your choosing to follow a
585
+ later version.
586
+
587
+ 15. Disclaimer of Warranty.
588
+
589
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
590
+ APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
591
+ HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
592
+ OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
593
+ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
594
+ PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
595
+ IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
596
+ ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
597
+
598
+ 16. Limitation of Liability.
599
+
600
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
601
+ WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
602
+ THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
603
+ GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
604
+ USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
605
+ DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
606
+ PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
607
+ EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
608
+ SUCH DAMAGES.
609
+
610
+ 17. Interpretation of Sections 15 and 16.
611
+
612
+ If the disclaimer of warranty and limitation of liability provided
613
+ above cannot be given local legal effect according to their terms,
614
+ reviewing courts shall apply local law that most closely approximates
615
+ an absolute waiver of all civil liability in connection with the
616
+ Program, unless a warranty or assumption of liability accompanies a
617
+ copy of the Program in return for a fee.
618
+
619
+ END OF TERMS AND CONDITIONS
620
+
621
+ How to Apply These Terms to Your New Programs
622
+
623
+ If you develop a new program, and you want it to be of the greatest
624
+ possible use to the public, the best way to achieve this is to make it
625
+ free software which everyone can redistribute and change under these terms.
626
+
627
+ To do so, attach the following notices to the program. It is safest
628
+ to attach them to the start of each source file to most effectively
629
+ state the exclusion of warranty; and each file should have at least
630
+ the "copyright" line and a pointer to where the full notice is found.
631
+
632
+ save what you love with cobalt.
633
+ Copyright (C) 2024 imput
634
+
635
+ This program is free software: you can redistribute it and/or modify
636
+ it under the terms of the GNU Affero General Public License as published by
637
+ the Free Software Foundation, either version 3 of the License, or
638
+ (at your option) any later version.
639
+
640
+ This program is distributed in the hope that it will be useful,
641
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
642
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
643
+ GNU Affero General Public License for more details.
644
+
645
+ You should have received a copy of the GNU Affero General Public License
646
+ along with this program. If not, see <https://www.gnu.org/licenses/>.
647
+
648
+ Also add information on how to contact you by electronic and paper mail.
649
+
650
+ If your software can interact with users remotely through a computer
651
+ network, you should also make sure that it provides a way for users to
652
+ get its source. For example, if your program is a web application, its
653
+ interface could display a "Source" link that leads users to an archive
654
+ of the code. There are many ways you could offer source, and different
655
+ solutions will be better for different programs; see section 13 for the
656
+ specific requirements.
657
+
658
+ You should also get your employer (if you work as a programmer) or school,
659
+ if any, to sign a "copyright disclaimer" for the program, if necessary.
660
+ For more information on this, and how to apply and follow the GNU AGPL, see
661
+ <https://www.gnu.org/licenses/>.
api/README.md ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # cobalt api
2
+
3
+ ## license
4
+ cobalt api code is licensed under [AGPL-3.0](LICENSE).
5
+
6
+ this license allows you to modify, distribute and use the code for any purpose
7
+ as long as you:
8
+ - give appropriate credit to the original repo when using or modifying any parts of the code,
9
+ - provide a link to the license and indicate if changes to the code were made, and
10
+ - release the code under the **same license**
11
+
12
+ ## running your own instance
13
+ if you want to run your own instance for whatever purpose, [follow this guide](/docs/run-an-instance.md).
14
+ it's *highly* recommended to use a docker compose method unless you run for developing/debugging purposes.
15
+
16
+ ## accessing the api
17
+ currently, there is no publicly accessible main api. we plan on providing a public api for
18
+ cobalt 10 in some form in the future. we recommend deploying your own instance if you wish
19
+ to use the latest api. you can access [the documentation](/docs/api.md) for it here.
20
+
21
+ if you are looking for the documentation for the old (7.x) api, you can find
22
+ it [here](https://github.com/imputnet/cobalt/blob/7/docs/api.md)
api/package.json ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "@imput/cobalt-api",
3
+ "description": "save what you love",
4
+ "version": "10.1.0",
5
+ "author": "imput",
6
+ "exports": "./src/cobalt.js",
7
+ "type": "module",
8
+ "engines": {
9
+ "node": ">=18"
10
+ },
11
+ "scripts": {
12
+ "start": "node src/cobalt",
13
+ "setup": "node src/util/setup",
14
+ "test": "node src/util/test",
15
+ "token:youtube": "node src/util/generate-youtube-tokens"
16
+ },
17
+ "repository": {
18
+ "type": "git",
19
+ "url": "git+https://github.com/imputnet/cobalt.git"
20
+ },
21
+ "license": "AGPL-3.0",
22
+ "bugs": {
23
+ "url": "https://github.com/imputnet/cobalt/issues"
24
+ },
25
+ "homepage": "https://github.com/imputnet/cobalt#readme",
26
+ "dependencies": {
27
+ "@imput/version-info": "workspace:^",
28
+ "content-disposition-header": "0.6.0",
29
+ "cors": "^2.8.5",
30
+ "dotenv": "^16.0.1",
31
+ "esbuild": "^0.14.51",
32
+ "express": "^4.18.1",
33
+ "express-rate-limit": "^6.3.0",
34
+ "ffmpeg-static": "^5.1.0",
35
+ "hls-parser": "^0.10.7",
36
+ "ipaddr.js": "2.1.0",
37
+ "nanoid": "^4.0.2",
38
+ "node-cache": "^5.1.2",
39
+ "psl": "1.9.0",
40
+ "set-cookie-parser": "2.6.0",
41
+ "undici": "^5.19.1",
42
+ "url-pattern": "1.0.3",
43
+ "youtubei.js": "^10.3.0",
44
+ "zod": "^3.23.8"
45
+ },
46
+ "optionalDependencies": {
47
+ "freebind": "^0.2.2"
48
+ }
49
+ }
api/src/cobalt.js ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import "dotenv/config";
2
+
3
+ import express from "express";
4
+
5
+ import path from 'path';
6
+ import { fileURLToPath } from 'url';
7
+
8
+ import { env } from "./config.js"
9
+ import { Bright, Green, Red } from "./misc/console-text.js";
10
+
11
+ const app = express();
12
+
13
+ const __filename = fileURLToPath(import.meta.url);
14
+ const __dirname = path.dirname(__filename).slice(0, -4);
15
+
16
+ app.disable('x-powered-by');
17
+
18
+ if (env.apiURL) {
19
+ const { runAPI } = await import('./core/api.js');
20
+ runAPI(express, app, __dirname)
21
+ } else {
22
+ console.log(
23
+ Red(`cobalt wasn't configured yet or configuration is invalid.\n`)
24
+ + Bright(`please run the setup script to fix this: `)
25
+ + Green(`npm run setup`)
26
+ )
27
+ }
api/src/config.js ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { getVersion } from "@imput/version-info";
2
+ import { services } from "./processing/service-config.js";
3
+
4
+ const version = await getVersion();
5
+
6
+ const disabledServices = process.env.DISABLED_SERVICES?.split(',') || [];
7
+ const enabledServices = new Set(Object.keys(services).filter(e => {
8
+ if (!disabledServices.includes(e)) {
9
+ return e;
10
+ }
11
+ }));
12
+
13
+ const env = {
14
+ apiURL: process.env.API_URL || '',
15
+ apiPort: process.env.API_PORT || 9000,
16
+
17
+ listenAddress: process.env.API_LISTEN_ADDRESS,
18
+ freebindCIDR: process.platform === 'linux' && process.env.FREEBIND_CIDR,
19
+
20
+ corsWildcard: process.env.CORS_WILDCARD !== '0',
21
+ corsURL: process.env.CORS_URL,
22
+
23
+ cookiePath: process.env.COOKIE_PATH,
24
+
25
+ rateLimitWindow: (process.env.RATELIMIT_WINDOW && parseInt(process.env.RATELIMIT_WINDOW)) || 60,
26
+ rateLimitMax: (process.env.RATELIMIT_MAX && parseInt(process.env.RATELIMIT_MAX)) || 20,
27
+
28
+ durationLimit: (process.env.DURATION_LIMIT && parseInt(process.env.DURATION_LIMIT)) || 10800,
29
+ streamLifespan: 90,
30
+
31
+ processingPriority: process.platform !== 'win32'
32
+ && process.env.PROCESSING_PRIORITY
33
+ && parseInt(process.env.PROCESSING_PRIORITY),
34
+
35
+ externalProxy: process.env.API_EXTERNAL_PROXY,
36
+
37
+ turnstileSitekey: process.env.TURNSTILE_SITEKEY,
38
+ turnstileSecret: process.env.TURNSTILE_SECRET,
39
+ jwtSecret: process.env.JWT_SECRET,
40
+ jwtLifetime: process.env.JWT_EXPIRY || 120,
41
+
42
+ sessionEnabled: process.env.TURNSTILE_SITEKEY
43
+ && process.env.TURNSTILE_SECRET
44
+ && process.env.JWT_SECRET,
45
+
46
+ enabledServices,
47
+ }
48
+
49
+ 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";
50
+ const cobaltUserAgent = `cobalt/${version} (+https://github.com/imputnet/cobalt)`;
51
+
52
+ export {
53
+ env,
54
+ genericUserAgent,
55
+ cobaltUserAgent,
56
+ }
api/src/core/api.js ADDED
@@ -0,0 +1,329 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cors from "cors";
2
+ import rateLimit from "express-rate-limit";
3
+ import { setGlobalDispatcher, ProxyAgent } from "undici";
4
+ import { getCommit, getBranch, getRemote, getVersion } from "@imput/version-info";
5
+
6
+ import jwt from "../security/jwt.js";
7
+ import stream from "../stream/stream.js";
8
+ import match from "../processing/match.js";
9
+
10
+ import { env } from "../config.js";
11
+ import { extract } from "../processing/url.js";
12
+ import { languageCode } from "../misc/utils.js";
13
+ import { Bright, Cyan } from "../misc/console-text.js";
14
+ import { generateHmac, generateSalt } from "../misc/crypto.js";
15
+ import { randomizeCiphers } from "../misc/randomize-ciphers.js";
16
+ import { verifyTurnstileToken } from "../security/turnstile.js";
17
+ import { friendlyServiceName } from "../processing/service-alias.js";
18
+ import { verifyStream, getInternalStream } from "../stream/manage.js";
19
+ import { createResponse, normalizeRequest, getIP } from "../processing/request.js";
20
+
21
+ const git = {
22
+ branch: await getBranch(),
23
+ commit: await getCommit(),
24
+ remote: await getRemote(),
25
+ }
26
+
27
+ const version = await getVersion();
28
+
29
+ const acceptRegex = /^application\/json(; charset=utf-8)?$/;
30
+
31
+ const ipSalt = generateSalt();
32
+ const corsConfig = env.corsWildcard ? {} : {
33
+ origin: env.corsURL,
34
+ optionsSuccessStatus: 200
35
+ }
36
+
37
+ const fail = (res, code, context) => {
38
+ const { status, body } = createResponse("error", { code, context });
39
+ res.status(status).json(body);
40
+ }
41
+
42
+ export const runAPI = (express, app, __dirname) => {
43
+ const startTime = new Date();
44
+ const startTimestamp = startTime.getTime();
45
+
46
+ const serverInfo = JSON.stringify({
47
+ cobalt: {
48
+ version: version,
49
+ url: env.apiURL,
50
+ startTime: `${startTimestamp}`,
51
+ durationLimit: env.durationLimit,
52
+ turnstileSitekey: env.sessionEnabled ? env.turnstileSitekey : undefined,
53
+ services: [...env.enabledServices].map(e => {
54
+ return friendlyServiceName(e);
55
+ }),
56
+ },
57
+ git,
58
+ })
59
+
60
+ const apiLimiter = rateLimit({
61
+ windowMs: env.rateLimitWindow * 1000,
62
+ max: env.rateLimitMax,
63
+ standardHeaders: true,
64
+ legacyHeaders: false,
65
+ keyGenerator: req => {
66
+ if (req.authorized) {
67
+ return generateHmac(req.header("Authorization"), ipSalt);
68
+ }
69
+ return generateHmac(getIP(req), ipSalt);
70
+ },
71
+ handler: (req, res) => {
72
+ const { status, body } = createResponse("error", {
73
+ code: "error.api.rate_exceeded",
74
+ context: {
75
+ limit: env.rateLimitWindow
76
+ }
77
+ });
78
+ return res.status(status).json(body);
79
+ }
80
+ })
81
+
82
+ const apiLimiterStream = rateLimit({
83
+ windowMs: env.rateLimitWindow * 1000,
84
+ max: env.rateLimitMax,
85
+ standardHeaders: true,
86
+ legacyHeaders: false,
87
+ keyGenerator: req => generateHmac(getIP(req), ipSalt),
88
+ handler: (req, res) => {
89
+ return res.sendStatus(429)
90
+ }
91
+ })
92
+
93
+ app.set('trust proxy', ['loopback', 'uniquelocal']);
94
+
95
+ app.use('/', cors({
96
+ methods: ['GET', 'POST'],
97
+ exposedHeaders: [
98
+ 'Ratelimit-Limit',
99
+ 'Ratelimit-Policy',
100
+ 'Ratelimit-Remaining',
101
+ 'Ratelimit-Reset'
102
+ ],
103
+ ...corsConfig,
104
+ }));
105
+
106
+ app.post('/', apiLimiter);
107
+ app.use('/tunnel', apiLimiterStream);
108
+
109
+ app.post('/', (req, res, next) => {
110
+ if (!acceptRegex.test(req.header('Accept'))) {
111
+ return fail(res, "error.api.header.accept");
112
+ }
113
+ if (!acceptRegex.test(req.header('Content-Type'))) {
114
+ return fail(res, "error.api.header.content_type");
115
+ }
116
+ next();
117
+ });
118
+
119
+ app.post('/', (req, res, next) => {
120
+ if (!env.sessionEnabled) {
121
+ return next();
122
+ }
123
+
124
+ try {
125
+ const authorization = req.header("Authorization");
126
+ if (!authorization) {
127
+ return fail(res, "error.api.auth.jwt.missing");
128
+ }
129
+
130
+ if (!authorization.startsWith("Bearer ") || authorization.length > 256) {
131
+ return fail(res, "error.api.auth.jwt.invalid");
132
+ }
133
+
134
+ const verifyJwt = jwt.verify(
135
+ authorization.split("Bearer ", 2)[1]
136
+ );
137
+
138
+ if (!verifyJwt) {
139
+ return fail(res, "error.api.auth.jwt.invalid");
140
+ }
141
+
142
+ req.authorized = true;
143
+ } catch {
144
+ return fail(res, "error.api.generic");
145
+ }
146
+ next();
147
+ });
148
+
149
+ app.use('/', express.json({ limit: 1024 }));
150
+ app.use('/', (err, _, res, next) => {
151
+ if (err) {
152
+ const { status, body } = createResponse("error", {
153
+ code: "error.api.invalid_body",
154
+ });
155
+ return res.status(status).json(body);
156
+ }
157
+
158
+ next();
159
+ });
160
+
161
+ app.post("/session", async (req, res) => {
162
+ if (!env.sessionEnabled) {
163
+ return fail(res, "error.api.auth.not_configured")
164
+ }
165
+
166
+ const turnstileResponse = req.header("cf-turnstile-response");
167
+
168
+ if (!turnstileResponse) {
169
+ return fail(res, "error.api.auth.turnstile.missing");
170
+ }
171
+
172
+ const turnstileResult = await verifyTurnstileToken(
173
+ turnstileResponse,
174
+ req.ip
175
+ );
176
+
177
+ if (!turnstileResult) {
178
+ return fail(res, "error.api.auth.turnstile.invalid");
179
+ }
180
+
181
+ try {
182
+ res.json(jwt.generate());
183
+ } catch {
184
+ return fail(res, "error.api.generic");
185
+ }
186
+ });
187
+
188
+ app.post('/', async (req, res) => {
189
+ const request = req.body;
190
+ const lang = languageCode(req);
191
+
192
+ if (!request.url) {
193
+ return fail(res, "error.api.link.missing");
194
+ }
195
+
196
+ if (request.youtubeDubBrowserLang) {
197
+ request.youtubeDubLang = lang;
198
+ }
199
+
200
+ const { success, data: normalizedRequest } = await normalizeRequest(request);
201
+ if (!success) {
202
+ return fail(res, "error.api.invalid_body");
203
+ }
204
+
205
+ const parsed = extract(normalizedRequest.url);
206
+
207
+ if (!parsed) {
208
+ return fail(res, "error.api.link.invalid");
209
+ }
210
+ if ("error" in parsed) {
211
+ let context;
212
+ if (parsed?.context) {
213
+ context = parsed.context;
214
+ }
215
+ return fail(res, `error.api.${parsed.error}`, context);
216
+ }
217
+
218
+ try {
219
+ const result = await match({
220
+ host: parsed.host,
221
+ patternMatch: parsed.patternMatch,
222
+ params: normalizedRequest,
223
+ });
224
+
225
+ res.status(result.status).json(result.body);
226
+ } catch {
227
+ fail(res, "error.api.generic");
228
+ }
229
+ })
230
+
231
+ app.get('/tunnel', (req, res) => {
232
+ const id = String(req.query.id);
233
+ const exp = String(req.query.exp);
234
+ const sig = String(req.query.sig);
235
+ const sec = String(req.query.sec);
236
+ const iv = String(req.query.iv);
237
+
238
+ const checkQueries = id && exp && sig && sec && iv;
239
+ const checkBaseLength = id.length === 21 && exp.length === 13;
240
+ const checkSafeLength = sig.length === 43 && sec.length === 43 && iv.length === 22;
241
+
242
+ if (!checkQueries || !checkBaseLength || !checkSafeLength) {
243
+ return res.status(400).end();
244
+ }
245
+
246
+ if (req.query.p) {
247
+ return res.status(200).end();
248
+ }
249
+
250
+ const streamInfo = verifyStream(id, sig, exp, sec, iv);
251
+ if (!streamInfo?.service) {
252
+ return res.status(streamInfo.status).end();
253
+ }
254
+
255
+ if (streamInfo.type === 'proxy') {
256
+ streamInfo.range = req.headers['range'];
257
+ }
258
+
259
+ return stream(res, streamInfo);
260
+ })
261
+
262
+ app.get('/itunnel', (req, res) => {
263
+ if (!req.ip.endsWith('127.0.0.1')) {
264
+ return res.sendStatus(403);
265
+ }
266
+
267
+ if (String(req.query.id).length !== 21) {
268
+ return res.sendStatus(400);
269
+ }
270
+
271
+ const streamInfo = getInternalStream(req.query.id);
272
+ if (!streamInfo) {
273
+ return res.sendStatus(404);
274
+ }
275
+
276
+ streamInfo.headers = new Map([
277
+ ...(streamInfo.headers || []),
278
+ ...Object.entries(req.headers)
279
+ ]);
280
+
281
+ return stream(res, { type: 'internal', ...streamInfo });
282
+ })
283
+
284
+ app.get('/', (_, res) => {
285
+ res.type('json');
286
+ res.status(200).send(serverInfo);
287
+ })
288
+
289
+ app.get('/favicon.ico', (req, res) => {
290
+ res.status(404).end();
291
+ })
292
+
293
+ app.get('/*', (req, res) => {
294
+ res.redirect('/');
295
+ })
296
+
297
+ // handle all express errors
298
+ app.use((_, __, res, ___) => {
299
+ return fail(res, "error.api.generic");
300
+ })
301
+
302
+ randomizeCiphers();
303
+ setInterval(randomizeCiphers, 1000 * 60 * 30); // shuffle ciphers every 30 minutes
304
+
305
+ if (env.externalProxy) {
306
+ if (env.freebindCIDR) {
307
+ throw new Error('Freebind is not available when external proxy is enabled')
308
+ }
309
+
310
+ setGlobalDispatcher(new ProxyAgent(env.externalProxy))
311
+ }
312
+
313
+ app.listen(env.apiPort, env.listenAddress, () => {
314
+ console.log(`\n` +
315
+ Bright(Cyan("cobalt ")) + Bright("API ^ω⁠^") + "\n" +
316
+
317
+ "~~~~~~\n" +
318
+ Bright("version: ") + version + "\n" +
319
+ Bright("commit: ") + git.commit + "\n" +
320
+ Bright("branch: ") + git.branch + "\n" +
321
+ Bright("remote: ") + git.remote + "\n" +
322
+ Bright("start time: ") + startTime.toUTCString() + "\n" +
323
+ "~~~~~~\n" +
324
+
325
+ Bright("url: ") + Bright(Cyan(env.apiURL)) + "\n" +
326
+ Bright("port: ") + env.apiPort + "\n"
327
+ )
328
+ })
329
+ }
api/src/misc/console-text.js ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ function t(color, tt) {
2
+ return color + tt + "\x1b[0m"
3
+ }
4
+
5
+ export function Bright(tt) {
6
+ return t("\x1b[1m", tt)
7
+ }
8
+ export function Red(tt) {
9
+ return t("\x1b[31m", tt)
10
+ }
11
+ export function Green(tt) {
12
+ return t("\x1b[32m", tt)
13
+ }
14
+ export function Cyan(tt) {
15
+ return t("\x1b[36m", tt)
16
+ }
api/src/misc/crypto.js ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { createHmac, createCipheriv, createDecipheriv, randomBytes } from "crypto";
2
+
3
+ const algorithm = "aes256";
4
+
5
+ export function generateSalt() {
6
+ return randomBytes(64).toString('hex');
7
+ }
8
+
9
+ export function generateHmac(str, salt) {
10
+ return createHmac("sha256", salt).update(str).digest("base64url");
11
+ }
12
+
13
+ export function encryptStream(plaintext, iv, secret) {
14
+ const buff = Buffer.from(JSON.stringify(plaintext));
15
+ const key = Buffer.from(secret, "base64url");
16
+ const cipher = createCipheriv(algorithm, key, Buffer.from(iv, "base64url"));
17
+
18
+ return Buffer.concat([ cipher.update(buff), cipher.final() ])
19
+ }
20
+
21
+ export function decryptStream(ciphertext, iv, secret) {
22
+ const buff = Buffer.from(ciphertext);
23
+ const key = Buffer.from(secret, "base64url");
24
+ const decipher = createDecipheriv(algorithm, key, Buffer.from(iv, "base64url"));
25
+
26
+ return Buffer.concat([ decipher.update(buff), decipher.final() ])
27
+ }
api/src/misc/load-from-fs.js ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import * as fs from "fs";
2
+ import { join, dirname } from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+
5
+ const root = join(
6
+ dirname(fileURLToPath(import.meta.url)),
7
+ '../../'
8
+ );
9
+
10
+ export function loadFile(path) {
11
+ return fs.readFileSync(join(root, path), 'utf-8')
12
+ }
13
+
14
+ export function loadJSON(path) {
15
+ try {
16
+ return JSON.parse(loadFile(path))
17
+ } catch {
18
+ return false
19
+ }
20
+ }
api/src/misc/randomize-ciphers.js ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import tls from 'node:tls';
2
+ import { randomBytes } from 'node:crypto';
3
+
4
+ const ORIGINAL_CIPHERS = tls.DEFAULT_CIPHERS;
5
+
6
+ // How many ciphers from the top of the list to shuffle.
7
+ // The remaining ciphers are left in the original order.
8
+ const TOP_N_SHUFFLE = 8;
9
+
10
+ // Modified variation of https://stackoverflow.com/a/12646864
11
+ const shuffleArray = (array) => {
12
+ for (let i = array.length - 1; i > 0; i--) {
13
+ const j = randomBytes(4).readUint32LE() % array.length;
14
+ [array[i], array[j]] = [array[j], array[i]];
15
+ }
16
+
17
+ return array;
18
+ }
19
+
20
+ export const randomizeCiphers = () => {
21
+ do {
22
+ const cipherList = ORIGINAL_CIPHERS.split(':');
23
+ const shuffled = shuffleArray(cipherList.slice(0, TOP_N_SHUFFLE));
24
+ const retained = cipherList.slice(TOP_N_SHUFFLE);
25
+
26
+ tls.DEFAULT_CIPHERS = [ ...shuffled, ...retained ].join(':');
27
+ } while (tls.DEFAULT_CIPHERS === ORIGINAL_CIPHERS);
28
+ }
api/src/misc/run-test.js ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { normalizeRequest } from "../processing/request.js";
2
+ import match from "../processing/match.js";
3
+ import { extract } from "../processing/url.js";
4
+
5
+ export async function runTest(url, params, expect) {
6
+ const { success, data: normalized } = await normalizeRequest({ url, ...params });
7
+ if (!success) {
8
+ throw "invalid request";
9
+ }
10
+
11
+ const parsed = extract(normalized.url);
12
+ if (parsed === null) {
13
+ throw `invalid url: ${normalized.url}`;
14
+ }
15
+
16
+ const result = await match({
17
+ host: parsed.host,
18
+ patternMatch: parsed.patternMatch,
19
+ params: normalized,
20
+ });
21
+
22
+ let error = [];
23
+ if (expect.status !== result.body.status) {
24
+ const detail = `${expect.status} (expected) != ${result.body.status} (actual)`;
25
+ error.push(`status mismatch: ${detail}`);
26
+ }
27
+
28
+ if (expect.code !== result.status) {
29
+ const detail = `${expect.code} (expected) != ${result.status} (actual)`;
30
+ error.push(`status code mismatch: ${detail}`);
31
+ }
32
+
33
+ if (error.length) {
34
+ if (result.body.text) {
35
+ error.push(`error message: ${result.body.text}`);
36
+ }
37
+
38
+ throw error.join('\n');
39
+ }
40
+
41
+ if (result.body.status === 'tunnel') {
42
+ // TODO: stream testing
43
+ }
44
+ }
api/src/misc/utils.js ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ const forbiddenCharsString = ['}', '{', '%', '>', '<', '^', ';', '`', '$', '"', "@", '='];
2
+
3
+ export function metadataManager(obj) {
4
+ const keys = Object.keys(obj);
5
+ const tags = [
6
+ "album",
7
+ "copyright",
8
+ "title",
9
+ "artist",
10
+ "track",
11
+ "date"
12
+ ]
13
+ let commands = []
14
+
15
+ for (const i in keys) {
16
+ if (tags.includes(keys[i]))
17
+ commands.push('-metadata', `${keys[i]}=${obj[keys[i]]}`)
18
+ }
19
+ return commands;
20
+ }
21
+
22
+ export function cleanString(string) {
23
+ for (const i in forbiddenCharsString) {
24
+ string = string.replaceAll("/", "_")
25
+ .replaceAll(forbiddenCharsString[i], '')
26
+ }
27
+ return string;
28
+ }
29
+ export function verifyLanguageCode(code) {
30
+ const langCode = String(code.slice(0, 2).toLowerCase());
31
+ if (RegExp(/[a-z]{2}/).test(code)) {
32
+ return langCode
33
+ }
34
+ return "en"
35
+ }
36
+ export function languageCode(req) {
37
+ if (req.header('Accept-Language')) {
38
+ return verifyLanguageCode(req.header('Accept-Language'))
39
+ }
40
+ return "en"
41
+ }
42
+ export function cleanHTML(html) {
43
+ let clean = html.replace(/ {4}/g, '');
44
+ clean = clean.replace(/\n/g, '');
45
+ return clean
46
+ }
47
+
48
+ export function getRedirectingURL(url) {
49
+ return fetch(url, { redirect: 'manual' }).then((r) => {
50
+ if ([301, 302, 303].includes(r.status) && r.headers.has('location'))
51
+ return r.headers.get('location');
52
+ }).catch(() => null);
53
+ }
54
+
55
+ export function merge(a, b) {
56
+ for (const k of Object.keys(b)) {
57
+ if (Array.isArray(b[k])) {
58
+ a[k] = [...(a[k] ?? []), ...b[k]];
59
+ } else if (typeof b[k] === 'object') {
60
+ a[k] = merge(a[k], b[k]);
61
+ } else {
62
+ a[k] = b[k];
63
+ }
64
+ }
65
+
66
+ return a;
67
+ }
68
+
69
+ export function splitFilenameExtension(filename) {
70
+ const parts = filename.split('.');
71
+ const ext = parts.pop();
72
+
73
+ if (!parts.length) {
74
+ return [ ext, "" ]
75
+ } else {
76
+ return [ parts.join('.'), ext ]
77
+ }
78
+ }
api/src/processing/cookie/cookie.js ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { strict as assert } from 'node:assert';
2
+
3
+ export default class Cookie {
4
+ constructor(input) {
5
+ assert(typeof input === 'object');
6
+ this._values = {};
7
+ this.set(input)
8
+ }
9
+ set(values) {
10
+ Object.entries(values).forEach(
11
+ ([ key, value ]) => this._values[key] = value
12
+ )
13
+ }
14
+ unset(keys) {
15
+ for (const key of keys) delete this._values[key]
16
+ }
17
+ static fromString(str) {
18
+ const obj = {};
19
+
20
+ str.split('; ').forEach(cookie => {
21
+ const key = cookie.split('=')[0];
22
+ const value = cookie.split('=').splice(1).join('=');
23
+ obj[key] = value
24
+ })
25
+
26
+ return new Cookie(obj)
27
+ }
28
+ toString() {
29
+ return Object.entries(this._values).map(([ name, value ]) => `${name}=${value}`).join('; ')
30
+ }
31
+ toJSON() {
32
+ return this.toString()
33
+ }
34
+ values() {
35
+ return Object.freeze({ ...this._values })
36
+ }
37
+ }
api/src/processing/cookie/manager.js ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import Cookie from './cookie.js';
2
+ import { readFile, writeFile } from 'fs/promises';
3
+ import { parse as parseSetCookie, splitCookiesString } from 'set-cookie-parser';
4
+ import { env } from '../../config.js';
5
+
6
+ const WRITE_INTERVAL = 60000,
7
+ cookiePath = env.cookiePath,
8
+ COUNTER = Symbol('counter');
9
+
10
+ let cookies = {}, dirty = false, intervalId;
11
+
12
+ const setup = async () => {
13
+ try {
14
+ if (!cookiePath) return;
15
+
16
+ cookies = await readFile(cookiePath, 'utf8');
17
+ cookies = JSON.parse(cookies);
18
+ intervalId = setInterval(writeChanges, WRITE_INTERVAL)
19
+ } catch { /* no cookies for you */ }
20
+ }
21
+
22
+ setup();
23
+
24
+ function writeChanges() {
25
+ if (!dirty) return;
26
+ dirty = false;
27
+
28
+ writeFile(cookiePath, JSON.stringify(cookies, null, 4)).catch(() => {
29
+ clearInterval(intervalId)
30
+ })
31
+ }
32
+
33
+ export function getCookie(service) {
34
+ if (!cookies[service] || !cookies[service].length) return;
35
+
36
+ let n;
37
+ if (cookies[service][COUNTER] === undefined) {
38
+ n = cookies[service][COUNTER] = 0
39
+ } else {
40
+ ++cookies[service][COUNTER]
41
+ n = (cookies[service][COUNTER] %= cookies[service].length)
42
+ }
43
+
44
+ const cookie = cookies[service][n];
45
+ if (typeof cookie === 'string') cookies[service][n] = Cookie.fromString(cookie);
46
+
47
+ return cookies[service][n]
48
+ }
49
+
50
+ export function updateCookie(cookie, headers) {
51
+ if (!cookie) return;
52
+
53
+ const parsed = parseSetCookie(
54
+ splitCookiesString(headers.get('set-cookie')),
55
+ { decodeValues: false }
56
+ ), values = {}
57
+
58
+ cookie.unset(parsed.filter(c => c.expires < new Date()).map(c => c.name));
59
+ parsed.filter(c => !c.expires || c.expires > new Date()).forEach(c => values[c.name] = c.value);
60
+ updateCookieValues(cookie, values);
61
+ }
62
+
63
+ export function updateCookieValues(cookie, values) {
64
+ cookie.set(values);
65
+ if (Object.keys(values).length) dirty = true
66
+ }
api/src/processing/create-filename.js ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ export default (f, style, isAudioOnly, isAudioMuted) => {
2
+ let filename = '';
3
+
4
+ let infoBase = [f.service, f.id];
5
+ let classicTags = [...infoBase];
6
+ let basicTags = [];
7
+
8
+ const title = `${f.title} - ${f.author}`;
9
+
10
+ if (f.resolution) {
11
+ classicTags.push(f.resolution);
12
+ }
13
+
14
+ if (f.qualityLabel) {
15
+ basicTags.push(f.qualityLabel);
16
+ }
17
+
18
+ if (f.youtubeFormat) {
19
+ classicTags.push(f.youtubeFormat);
20
+ basicTags.push(f.youtubeFormat);
21
+ }
22
+
23
+ if (isAudioMuted) {
24
+ classicTags.push("mute");
25
+ basicTags.push("mute");
26
+ } else if (f.youtubeDubName) {
27
+ classicTags.push(f.youtubeDubName);
28
+ basicTags.push(f.youtubeDubName);
29
+ }
30
+
31
+ switch (style) {
32
+ default:
33
+ case "classic":
34
+ if (isAudioOnly) {
35
+ if (f.youtubeDubName) {
36
+ infoBase.push(f.youtubeDubName);
37
+ }
38
+ return `${infoBase.join("_")}_audio`;
39
+ }
40
+ filename = classicTags.join("_");
41
+ break;
42
+ case "basic":
43
+ if (isAudioOnly) return title;
44
+ filename = `${title} (${basicTags.join(", ")})`;
45
+ break;
46
+ case "pretty":
47
+ if (isAudioOnly) return `${title} (${infoBase[0]})`;
48
+ filename = `${title} (${[...basicTags, infoBase[0]].join(", ")})`;
49
+ break;
50
+ case "nerdy":
51
+ if (isAudioOnly) return `${title} (${infoBase.join(", ")})`;
52
+ filename = `${title} (${basicTags.concat(infoBase).join(", ")})`;
53
+ break;
54
+ }
55
+ return `${filename}.${f.extension}`;
56
+ }
api/src/processing/match-action.js ADDED
@@ -0,0 +1,212 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import createFilename from "./create-filename.js";
2
+
3
+ import { createResponse } from "./request.js";
4
+ import { audioIgnore } from "./service-config.js";
5
+ import { createStream } from "../stream/manage.js";
6
+ import { splitFilenameExtension } from "../misc/utils.js";
7
+
8
+ export default function({ r, host, audioFormat, isAudioOnly, isAudioMuted, disableMetadata, filenameStyle, twitterGif, requestIP, audioBitrate, alwaysProxy }) {
9
+ let action,
10
+ responseType = "tunnel",
11
+ defaultParams = {
12
+ u: r.urls,
13
+ headers: r.headers,
14
+ service: host,
15
+ filename: r.filenameAttributes ?
16
+ createFilename(r.filenameAttributes, filenameStyle, isAudioOnly, isAudioMuted) : r.filename,
17
+ fileMetadata: !disableMetadata ? r.fileMetadata : false,
18
+ requestIP
19
+ },
20
+ params = {};
21
+
22
+ if (r.isPhoto) action = "photo";
23
+ else if (r.picker) action = "picker"
24
+ else if (r.isGif && twitterGif) action = "gif";
25
+ else if (isAudioOnly) action = "audio";
26
+ else if (isAudioMuted) action = "muteVideo";
27
+ else if (r.isM3U8) action = "m3u8";
28
+ else action = "video";
29
+
30
+ if (action === "picker" || action === "audio") {
31
+ if (!r.filenameAttributes) defaultParams.filename = r.audioFilename;
32
+ defaultParams.audioFormat = audioFormat;
33
+ }
34
+
35
+ if (action === "muteVideo" && isAudioMuted && !r.filenameAttributes) {
36
+ const [ name, ext ] = splitFilenameExtension(r.filename);
37
+ defaultParams.filename = `${name}_mute.${ext}`;
38
+ } else if (action === "gif") {
39
+ const [ name ] = splitFilenameExtension(r.filename);
40
+ defaultParams.filename = `${name}.gif`;
41
+ }
42
+
43
+ switch (action) {
44
+ default:
45
+ return createResponse("error", {
46
+ code: "error.api.fetch.empty"
47
+ });
48
+
49
+ case "photo":
50
+ responseType = "redirect";
51
+ break;
52
+
53
+ case "gif":
54
+ params = { type: "gif" };
55
+ break;
56
+
57
+ case "m3u8":
58
+ params = {
59
+ type: Array.isArray(r.urls) ? "merge" : "remux"
60
+ }
61
+ break;
62
+
63
+ case "muteVideo":
64
+ let muteType = "mute";
65
+ if (Array.isArray(r.urls) && !r.isM3U8) {
66
+ muteType = "proxy";
67
+ }
68
+ params = {
69
+ type: muteType,
70
+ u: Array.isArray(r.urls) ? r.urls[0] : r.urls
71
+ }
72
+ if (host === "reddit" && r.typeId === "redirect") {
73
+ responseType = "redirect";
74
+ }
75
+ break;
76
+
77
+ case "picker":
78
+ responseType = "picker";
79
+ switch (host) {
80
+ case "instagram":
81
+ case "twitter":
82
+ case "snapchat":
83
+ case "bsky":
84
+ params = { picker: r.picker };
85
+ break;
86
+
87
+ case "tiktok":
88
+ let audioStreamType = "audio";
89
+ if (r.bestAudio === "mp3" && audioFormat === "best") {
90
+ audioFormat = "mp3";
91
+ audioStreamType = "proxy"
92
+ }
93
+ params = {
94
+ picker: r.picker,
95
+ u: createStream({
96
+ service: "tiktok",
97
+ type: audioStreamType,
98
+ u: r.urls,
99
+ headers: r.headers,
100
+ filename: r.audioFilename,
101
+ isAudioOnly: true,
102
+ audioFormat,
103
+ })
104
+ }
105
+ break;
106
+ }
107
+ break;
108
+
109
+ case "video":
110
+ switch (host) {
111
+ case "bilibili":
112
+ params = { type: "merge" };
113
+ break;
114
+
115
+ case "youtube":
116
+ params = { type: r.type };
117
+ break;
118
+
119
+ case "reddit":
120
+ responseType = r.typeId;
121
+ params = { type: r.type };
122
+ break;
123
+
124
+ case "vimeo":
125
+ if (Array.isArray(r.urls)) {
126
+ params = { type: "merge" }
127
+ } else {
128
+ responseType = "redirect";
129
+ }
130
+ break;
131
+
132
+ case "twitter":
133
+ if (r.type === "remux") {
134
+ params = { type: r.type };
135
+ } else {
136
+ responseType = "redirect";
137
+ }
138
+ break;
139
+
140
+ case "vk":
141
+ case "tiktok":
142
+ params = { type: "proxy" };
143
+ break;
144
+
145
+ case "facebook":
146
+ case "vine":
147
+ case "instagram":
148
+ case "tumblr":
149
+ case "pinterest":
150
+ case "streamable":
151
+ case "snapchat":
152
+ case "loom":
153
+ case "twitch":
154
+ responseType = "redirect";
155
+ break;
156
+ }
157
+ break;
158
+
159
+ case "audio":
160
+ if (audioIgnore.includes(host) || (host === "reddit" && r.typeId === "redirect")) {
161
+ return createResponse("error", {
162
+ code: "error.api.fetch.empty"
163
+ })
164
+ }
165
+
166
+ let processType = "audio";
167
+ let copy = false;
168
+
169
+ if (audioFormat === "best") {
170
+ const serviceBestAudio = r.bestAudio;
171
+
172
+ if (serviceBestAudio) {
173
+ audioFormat = serviceBestAudio;
174
+ processType = "proxy";
175
+
176
+ if (host === "soundcloud") {
177
+ processType = "audio";
178
+ copy = true;
179
+ }
180
+ } else {
181
+ audioFormat = "m4a";
182
+ copy = true;
183
+ }
184
+ }
185
+
186
+ if (r.isM3U8 || host === "vimeo") {
187
+ copy = false;
188
+ processType = "audio";
189
+ }
190
+
191
+ params = {
192
+ type: processType,
193
+ u: Array.isArray(r.urls) ? r.urls[1] : r.urls,
194
+
195
+ audioBitrate,
196
+ audioCopy: copy,
197
+ audioFormat,
198
+ }
199
+ break;
200
+ }
201
+
202
+ if (defaultParams.filename && (action === "picker" || action === "audio")) {
203
+ defaultParams.filename += `.${audioFormat}`;
204
+ }
205
+
206
+ if (alwaysProxy && responseType === "redirect") {
207
+ responseType = "tunnel";
208
+ params.type = "proxy";
209
+ }
210
+
211
+ return createResponse(responseType, {...defaultParams, ...params})
212
+ }
api/src/processing/match.js ADDED
@@ -0,0 +1,310 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { strict as assert } from "node:assert";
2
+
3
+ import { env } from "../config.js";
4
+ import { createResponse } from "../processing/request.js";
5
+
6
+ import { testers } from "./service-patterns.js";
7
+ import matchAction from "./match-action.js";
8
+
9
+ import { friendlyServiceName } from "./service-alias.js";
10
+
11
+ import bilibili from "./services/bilibili.js";
12
+ import reddit from "./services/reddit.js";
13
+ import twitter from "./services/twitter.js";
14
+ import youtube from "./services/youtube.js";
15
+ import vk from "./services/vk.js";
16
+ import ok from "./services/ok.js";
17
+ import tiktok from "./services/tiktok.js";
18
+ import tumblr from "./services/tumblr.js";
19
+ import vimeo from "./services/vimeo.js";
20
+ import soundcloud from "./services/soundcloud.js";
21
+ import instagram from "./services/instagram.js";
22
+ import vine from "./services/vine.js";
23
+ import pinterest from "./services/pinterest.js";
24
+ import streamable from "./services/streamable.js";
25
+ import twitch from "./services/twitch.js";
26
+ import rutube from "./services/rutube.js";
27
+ import dailymotion from "./services/dailymotion.js";
28
+ import snapchat from "./services/snapchat.js";
29
+ import loom from "./services/loom.js";
30
+ import facebook from "./services/facebook.js";
31
+ import bluesky from "./services/bluesky.js";
32
+
33
+ let freebind;
34
+
35
+ export default async function({ host, patternMatch, params }) {
36
+ const { url } = params;
37
+ assert(url instanceof URL);
38
+ let dispatcher, requestIP;
39
+
40
+ if (env.freebindCIDR) {
41
+ if (!freebind) {
42
+ freebind = await import('freebind');
43
+ }
44
+
45
+ requestIP = freebind.ip.random(env.freebindCIDR);
46
+ dispatcher = freebind.dispatcherFromIP(requestIP, { strict: false });
47
+ }
48
+
49
+ try {
50
+ let r,
51
+ isAudioOnly = params.downloadMode === "audio",
52
+ isAudioMuted = params.downloadMode === "mute";
53
+
54
+ if (!testers[host]) {
55
+ return createResponse("error", {
56
+ code: "error.api.service.unsupported"
57
+ });
58
+ }
59
+ if (!(testers[host](patternMatch))) {
60
+ return createResponse("error", {
61
+ code: "error.api.link.unsupported",
62
+ context: {
63
+ service: friendlyServiceName(host),
64
+ }
65
+ });
66
+ }
67
+
68
+ switch (host) {
69
+ case "twitter":
70
+ r = await twitter({
71
+ id: patternMatch.id,
72
+ index: patternMatch.index - 1,
73
+ toGif: !!params.twitterGif,
74
+ alwaysProxy: params.alwaysProxy,
75
+ dispatcher
76
+ });
77
+ break;
78
+
79
+ case "vk":
80
+ r = await vk({
81
+ userId: patternMatch.userId,
82
+ videoId: patternMatch.videoId,
83
+ quality: params.videoQuality
84
+ });
85
+ break;
86
+
87
+ case "ok":
88
+ r = await ok({
89
+ id: patternMatch.id,
90
+ quality: params.videoQuality
91
+ });
92
+ break;
93
+
94
+ case "bilibili":
95
+ r = await bilibili(patternMatch);
96
+ break;
97
+
98
+ case "youtube":
99
+ let fetchInfo = {
100
+ id: patternMatch.id.slice(0, 11),
101
+ quality: params.videoQuality,
102
+ format: params.youtubeVideoCodec,
103
+ isAudioOnly,
104
+ isAudioMuted,
105
+ dubLang: params.youtubeDubLang,
106
+ dispatcher
107
+ }
108
+
109
+ if (url.hostname === "music.youtube.com" || isAudioOnly) {
110
+ fetchInfo.quality = "max";
111
+ fetchInfo.format = "vp9";
112
+ fetchInfo.isAudioOnly = true;
113
+ fetchInfo.isAudioMuted = false;
114
+ }
115
+
116
+ r = await youtube(fetchInfo);
117
+ break;
118
+
119
+ case "reddit":
120
+ r = await reddit({
121
+ sub: patternMatch.sub,
122
+ id: patternMatch.id,
123
+ user: patternMatch.user
124
+ });
125
+ break;
126
+
127
+ case "tiktok":
128
+ r = await tiktok({
129
+ postId: patternMatch.postId,
130
+ id: patternMatch.id,
131
+ fullAudio: params.tiktokFullAudio,
132
+ isAudioOnly,
133
+ h265: params.tiktokH265,
134
+ alwaysProxy: params.alwaysProxy,
135
+ });
136
+ break;
137
+
138
+ case "tumblr":
139
+ r = await tumblr({
140
+ id: patternMatch.id,
141
+ user: patternMatch.user,
142
+ url
143
+ });
144
+ break;
145
+
146
+ case "vimeo":
147
+ r = await vimeo({
148
+ id: patternMatch.id.slice(0, 11),
149
+ password: patternMatch.password,
150
+ quality: params.videoQuality,
151
+ isAudioOnly,
152
+ });
153
+ break;
154
+
155
+ case "soundcloud":
156
+ isAudioOnly = true;
157
+ isAudioMuted = false;
158
+ r = await soundcloud({
159
+ url,
160
+ author: patternMatch.author,
161
+ song: patternMatch.song,
162
+ format: params.audioFormat,
163
+ shortLink: patternMatch.shortLink || false,
164
+ accessKey: patternMatch.accessKey || false
165
+ });
166
+ break;
167
+
168
+ case "instagram":
169
+ r = await instagram({
170
+ ...patternMatch,
171
+ quality: params.videoQuality,
172
+ alwaysProxy: params.alwaysProxy,
173
+ dispatcher
174
+ })
175
+ break;
176
+
177
+ case "vine":
178
+ r = await vine({
179
+ id: patternMatch.id
180
+ });
181
+ break;
182
+
183
+ case "pinterest":
184
+ r = await pinterest({
185
+ id: patternMatch.id,
186
+ shortLink: patternMatch.shortLink || false
187
+ });
188
+ break;
189
+
190
+ case "streamable":
191
+ r = await streamable({
192
+ id: patternMatch.id,
193
+ quality: params.videoQuality,
194
+ isAudioOnly,
195
+ });
196
+ break;
197
+
198
+ case "twitch":
199
+ r = await twitch({
200
+ clipId: patternMatch.clip || false,
201
+ quality: params.videoQuality,
202
+ isAudioOnly,
203
+ });
204
+ break;
205
+
206
+ case "rutube":
207
+ r = await rutube({
208
+ id: patternMatch.id,
209
+ yappyId: patternMatch.yappyId,
210
+ key: patternMatch.key,
211
+ quality: params.videoQuality,
212
+ isAudioOnly,
213
+ });
214
+ break;
215
+
216
+ case "dailymotion":
217
+ r = await dailymotion(patternMatch);
218
+ break;
219
+
220
+ case "snapchat":
221
+ r = await snapchat({
222
+ ...patternMatch,
223
+ alwaysProxy: params.alwaysProxy,
224
+ });
225
+ break;
226
+
227
+ case "loom":
228
+ r = await loom({
229
+ id: patternMatch.id
230
+ });
231
+ break;
232
+
233
+ case "facebook":
234
+ r = await facebook({
235
+ ...patternMatch
236
+ });
237
+ break;
238
+
239
+ case "bsky":
240
+ r = await bluesky({
241
+ ...patternMatch,
242
+ alwaysProxy: params.alwaysProxy
243
+ });
244
+ break;
245
+
246
+ default:
247
+ return createResponse("error", {
248
+ code: "error.api.service.unsupported"
249
+ });
250
+ }
251
+
252
+ if (r.isAudioOnly) {
253
+ isAudioOnly = true;
254
+ isAudioMuted = false;
255
+ }
256
+
257
+ if (r.error && r.critical) {
258
+ return createResponse("critical", {
259
+ code: `error.api.${r.error}`,
260
+ })
261
+ }
262
+
263
+ if (r.error) {
264
+ let context;
265
+ switch(r.error) {
266
+ case "content.too_long":
267
+ context = {
268
+ limit: env.durationLimit / 60,
269
+ }
270
+ break;
271
+
272
+ case "fetch.fail":
273
+ case "fetch.rate":
274
+ case "fetch.critical":
275
+ case "link.unsupported":
276
+ case "content.video.unavailable":
277
+ context = {
278
+ service: friendlyServiceName(host),
279
+ }
280
+ break;
281
+ }
282
+
283
+ return createResponse("error", {
284
+ code: `error.api.${r.error}`,
285
+ context,
286
+ })
287
+ }
288
+
289
+ return matchAction({
290
+ r,
291
+ host,
292
+ audioFormat: params.audioFormat,
293
+ isAudioOnly,
294
+ isAudioMuted,
295
+ disableMetadata: params.disableMetadata,
296
+ filenameStyle: params.filenameStyle,
297
+ twitterGif: params.twitterGif,
298
+ requestIP,
299
+ audioBitrate: params.audioBitrate,
300
+ alwaysProxy: params.alwaysProxy,
301
+ })
302
+ } catch {
303
+ return createResponse("error", {
304
+ code: "error.api.fetch.critical",
305
+ context: {
306
+ service: friendlyServiceName(host),
307
+ }
308
+ })
309
+ }
310
+ }
api/src/processing/request.js ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import ipaddr from "ipaddr.js";
2
+
3
+ import { createStream } from "../stream/manage.js";
4
+ import { apiSchema } from "./schema.js";
5
+
6
+ export function createResponse(responseType, responseData) {
7
+ const internalError = (code) => {
8
+ return {
9
+ status: 500,
10
+ body: {
11
+ status: "error",
12
+ error: {
13
+ code: code || "error.api.fetch.critical",
14
+ },
15
+ critical: true
16
+ }
17
+ }
18
+ }
19
+
20
+ try {
21
+ let status = 200,
22
+ response = {};
23
+
24
+ if (responseType === "error") {
25
+ status = 400;
26
+ }
27
+
28
+ switch (responseType) {
29
+ case "error":
30
+ response = {
31
+ error: {
32
+ code: responseData?.code,
33
+ context: responseData?.context,
34
+ }
35
+ }
36
+ break;
37
+
38
+ case "redirect":
39
+ response = {
40
+ url: responseData?.u,
41
+ filename: responseData?.filename
42
+ }
43
+ break;
44
+
45
+ case "tunnel":
46
+ response = {
47
+ url: createStream(responseData),
48
+ filename: responseData?.filename
49
+ }
50
+ break;
51
+
52
+ case "picker":
53
+ response = {
54
+ picker: responseData?.picker,
55
+ audio: responseData?.u,
56
+ audioFilename: responseData?.filename
57
+ }
58
+ break;
59
+
60
+ case "critical":
61
+ return internalError(responseData?.code);
62
+
63
+ default:
64
+ throw "unreachable"
65
+ }
66
+
67
+ return {
68
+ status,
69
+ body: {
70
+ status: responseType,
71
+ ...response
72
+ }
73
+ }
74
+ } catch {
75
+ return internalError()
76
+ }
77
+ }
78
+
79
+ export function normalizeRequest(request) {
80
+ return apiSchema.safeParseAsync(request).catch(() => (
81
+ { success: false }
82
+ ));
83
+ }
84
+
85
+ export function getIP(req) {
86
+ const strippedIP = req.ip.replace(/^::ffff:/, '');
87
+ const ip = ipaddr.parse(strippedIP);
88
+ if (ip.kind() === 'ipv4') {
89
+ return strippedIP;
90
+ }
91
+
92
+ const prefix = 56;
93
+ const v6Bytes = ip.toByteArray();
94
+ v6Bytes.fill(0, prefix / 8);
95
+
96
+ return ipaddr.fromByteArray(v6Bytes).toString();
97
+ }
api/src/processing/schema.js ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { z } from "zod";
2
+
3
+ import { normalizeURL } from "./url.js";
4
+ import { verifyLanguageCode } from "../misc/utils.js";
5
+
6
+ export const apiSchema = z.object({
7
+ url: z.string()
8
+ .min(1)
9
+ .transform(url => normalizeURL(url)),
10
+
11
+ audioBitrate: z.enum(
12
+ ["320", "256", "128", "96", "64", "8"]
13
+ ).default("128"),
14
+
15
+ audioFormat: z.enum(
16
+ ["best", "mp3", "ogg", "wav", "opus"]
17
+ ).default("mp3"),
18
+
19
+ downloadMode: z.enum(
20
+ ["auto", "audio", "mute"]
21
+ ).default("auto"),
22
+
23
+ filenameStyle: z.enum(
24
+ ["classic", "pretty", "basic", "nerdy"]
25
+ ).default("classic"),
26
+
27
+ youtubeVideoCodec: z.enum(
28
+ ["h264", "av1", "vp9"]
29
+ ).default("h264"),
30
+
31
+ videoQuality: z.enum(
32
+ ["max", "4320", "2160", "1440", "1080", "720", "480", "360", "240", "144"]
33
+ ).default("1080"),
34
+
35
+ youtubeDubLang: z.string()
36
+ .length(2)
37
+ .transform(verifyLanguageCode)
38
+ .optional(),
39
+
40
+ alwaysProxy: z.boolean().default(false),
41
+ disableMetadata: z.boolean().default(false),
42
+ tiktokFullAudio: z.boolean().default(false),
43
+ tiktokH265: z.boolean().default(false),
44
+ twitterGif: z.boolean().default(true),
45
+ youtubeDubBrowserLang: z.boolean().default(false),
46
+ })
47
+ .strict();
api/src/processing/service-alias.js ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ const friendlyNames = {
2
+ bsky: "bluesky",
3
+ }
4
+
5
+ export const friendlyServiceName = (service) => {
6
+ if (service in friendlyNames) {
7
+ return friendlyNames[service];
8
+ }
9
+ return service;
10
+ }
api/src/processing/service-config.js ADDED
@@ -0,0 +1,182 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import UrlPattern from "url-pattern";
2
+
3
+ export const audioIgnore = ["vk", "ok", "loom"];
4
+ export const hlsExceptions = ["dailymotion", "vimeo", "rutube", "bsky"];
5
+
6
+ export const services = {
7
+ bilibili: {
8
+ patterns: [
9
+ "video/:comId",
10
+ "_shortLink/:comShortLink",
11
+ "_tv/:lang/video/:tvId",
12
+ "_tv/video/:tvId"
13
+ ],
14
+ subdomains: ["m"],
15
+ },
16
+ bsky: {
17
+ patterns: [
18
+ "profile/:user/post/:post"
19
+ ],
20
+ tld: "app",
21
+ },
22
+ dailymotion: {
23
+ patterns: ["video/:id"],
24
+ },
25
+ facebook: {
26
+ patterns: [
27
+ "_shortLink/:shortLink",
28
+ ":username/videos/:caption/:id",
29
+ ":username/videos/:id",
30
+ "reel/:id",
31
+ "share/:shareType/:id"
32
+ ],
33
+ subdomains: ["web"],
34
+ altDomains: ["fb.watch"],
35
+ },
36
+ instagram: {
37
+ patterns: [
38
+ "reels/:postId",
39
+ ":username/reel/:postId",
40
+ "reel/:postId",
41
+ "p/:postId",
42
+ ":username/p/:postId",
43
+ "tv/:postId",
44
+ "stories/:username/:storyId"
45
+ ],
46
+ altDomains: ["ddinstagram.com"],
47
+ },
48
+ loom: {
49
+ patterns: ["share/:id"],
50
+ },
51
+ ok: {
52
+ patterns: [
53
+ "video/:id",
54
+ "videoembed/:id"
55
+ ],
56
+ tld: "ru",
57
+ },
58
+ pinterest: {
59
+ patterns: [
60
+ "pin/:id",
61
+ "pin/:id/:garbage",
62
+ "url_shortener/:shortLink"
63
+ ],
64
+ },
65
+ reddit: {
66
+ patterns: [
67
+ "r/:sub/comments/:id/:title",
68
+ "user/:user/comments/:id/:title"
69
+ ],
70
+ subdomains: "*",
71
+ },
72
+ rutube: {
73
+ patterns: [
74
+ "video/:id",
75
+ "play/embed/:id",
76
+ "shorts/:id",
77
+ "yappy/:yappyId",
78
+ "video/private/:id?p=:key",
79
+ "video/private/:id"
80
+ ],
81
+ tld: "ru",
82
+ },
83
+ snapchat: {
84
+ patterns: [
85
+ ":shortLink",
86
+ "spotlight/:spotlightId",
87
+ "add/:username/:storyId",
88
+ "u/:username/:storyId",
89
+ "add/:username",
90
+ "u/:username",
91
+ "t/:shortLink",
92
+ ],
93
+ subdomains: ["t", "story"],
94
+ },
95
+ soundcloud: {
96
+ patterns: [
97
+ ":author/:song/s-:accessKey",
98
+ ":author/:song",
99
+ ":shortLink"
100
+ ],
101
+ subdomains: ["on", "m"],
102
+ },
103
+ streamable: {
104
+ patterns: [
105
+ ":id",
106
+ "o/:id",
107
+ "e/:id",
108
+ "s/:id"
109
+ ],
110
+ },
111
+ tiktok: {
112
+ patterns: [
113
+ ":user/video/:postId",
114
+ ":id",
115
+ "t/:id",
116
+ ":user/photo/:postId",
117
+ "v/:id.html"
118
+ ],
119
+ subdomains: ["vt", "vm", "m"],
120
+ },
121
+ tumblr: {
122
+ patterns: [
123
+ "post/:id",
124
+ "blog/view/:user/:id",
125
+ ":user/:id",
126
+ ":user/:id/:trackingId"
127
+ ],
128
+ subdomains: "*",
129
+ },
130
+ twitch: {
131
+ patterns: [":channel/clip/:clip"],
132
+ tld: "tv",
133
+ },
134
+ twitter: {
135
+ patterns: [
136
+ ":user/status/:id",
137
+ ":user/status/:id/video/:index",
138
+ ":user/status/:id/photo/:index",
139
+ ":user/status/:id/mediaviewer",
140
+ ":user/status/:id/mediaViewer"
141
+ ],
142
+ subdomains: ["mobile"],
143
+ altDomains: ["x.com", "vxtwitter.com", "fixvx.com"],
144
+ },
145
+ vine: {
146
+ patterns: ["v/:id"],
147
+ tld: "co",
148
+ },
149
+ vimeo: {
150
+ patterns: [
151
+ ":id",
152
+ "video/:id",
153
+ ":id/:password",
154
+ "/channels/:user/:id"
155
+ ],
156
+ subdomains: ["player"],
157
+ },
158
+ vk: {
159
+ patterns: [
160
+ "video:userId_:videoId",
161
+ "clip:userId_:videoId",
162
+ "clips:duplicate?z=clip:userId_:videoId"
163
+ ],
164
+ subdomains: ["m"],
165
+ },
166
+ youtube: {
167
+ patterns: [
168
+ "watch?v=:id",
169
+ "embed/:id",
170
+ "watch/:id"
171
+ ],
172
+ subdomains: ["music", "m"],
173
+ }
174
+ }
175
+
176
+ Object.values(services).forEach(service => {
177
+ service.patterns = service.patterns.map(
178
+ pattern => new UrlPattern(pattern, {
179
+ segmentValueCharset: UrlPattern.defaultOptions.segmentValueCharset + '@\\.:'
180
+ })
181
+ )
182
+ })
api/src/processing/service-patterns.js ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ export const testers = {
2
+ "bilibili": pattern =>
3
+ pattern.comId?.length <= 12 || pattern.comShortLink?.length <= 16
4
+ || pattern.tvId?.length <= 24,
5
+
6
+ "dailymotion": pattern => pattern.id?.length <= 32,
7
+
8
+ "instagram": pattern =>
9
+ pattern.postId?.length <= 12
10
+ || (pattern.username?.length <= 30 && pattern.storyId?.length <= 24),
11
+
12
+ "loom": pattern =>
13
+ pattern.id?.length <= 32,
14
+
15
+ "ok": pattern =>
16
+ pattern.id?.length <= 16,
17
+
18
+ "pinterest": pattern =>
19
+ pattern.id?.length <= 128 || pattern.shortLink?.length <= 32,
20
+
21
+ "reddit": pattern =>
22
+ (pattern.sub?.length <= 22 && pattern.id?.length <= 10)
23
+ || (pattern.user?.length <= 22 && pattern.id?.length <= 10),
24
+
25
+ "rutube": pattern =>
26
+ (pattern.id?.length === 32 && pattern.key?.length <= 32) ||
27
+ pattern.id?.length === 32 || pattern.yappyId?.length === 32,
28
+
29
+ "soundcloud": pattern =>
30
+ (pattern.author?.length <= 255 && pattern.song?.length <= 255)
31
+ || pattern.shortLink?.length <= 32,
32
+
33
+ "snapchat": pattern =>
34
+ (pattern.username?.length <= 32 && (!pattern.storyId || pattern.storyId?.length <= 255))
35
+ || pattern.spotlightId?.length <= 255
36
+ || pattern.shortLink?.length <= 16,
37
+
38
+ "streamable": pattern =>
39
+ pattern.id?.length === 6,
40
+
41
+ "tiktok": pattern =>
42
+ pattern.postId?.length <= 21 || pattern.id?.length <= 13,
43
+
44
+ "tumblr": pattern =>
45
+ pattern.id?.length < 21
46
+ || (pattern.id?.length < 21 && pattern.user?.length <= 32),
47
+
48
+ "twitch": pattern =>
49
+ pattern.channel && pattern.clip?.length <= 100,
50
+
51
+ "twitter": pattern =>
52
+ pattern.id?.length < 20,
53
+
54
+ "vimeo": pattern =>
55
+ pattern.id?.length <= 11
56
+ && (!pattern.password || pattern.password.length < 16),
57
+
58
+ "vine": pattern =>
59
+ pattern.id?.length <= 12,
60
+
61
+ "vk": pattern =>
62
+ pattern.userId?.length <= 10 && pattern.videoId?.length <= 10,
63
+
64
+ "youtube": pattern =>
65
+ pattern.id?.length <= 11,
66
+
67
+ "facebook": pattern =>
68
+ pattern.shortLink?.length <= 11
69
+ || pattern.username?.length <= 30
70
+ || pattern.caption?.length <= 255
71
+ || pattern.id?.length <= 20 && !pattern.shareType
72
+ || pattern.id?.length <= 20 && pattern.shareType?.length === 1,
73
+
74
+ "bsky": pattern =>
75
+ pattern.user?.length <= 128 && pattern.post?.length <= 128,
76
+ }
api/src/processing/services/bilibili.js ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { genericUserAgent, env } from "../../config.js";
2
+
3
+ // TO-DO: higher quality downloads (currently requires an account)
4
+
5
+ function com_resolveShortlink(shortId) {
6
+ return fetch(`https://b23.tv/${shortId}`, { redirect: 'manual' })
7
+ .then(r => r.status > 300 && r.status < 400 && r.headers.get('location'))
8
+ .then(url => {
9
+ if (!url) return;
10
+ const path = new URL(url).pathname;
11
+ if (path.startsWith('/video/'))
12
+ return path.split('/')[2];
13
+ })
14
+ .catch(() => {})
15
+ }
16
+
17
+ function getBest(content) {
18
+ return content?.filter(v => v.baseUrl || v.url)
19
+ .map(v => (v.baseUrl = v.baseUrl || v.url, v))
20
+ .reduce((a, b) => a?.bandwidth > b?.bandwidth ? a : b);
21
+ }
22
+
23
+ function extractBestQuality(dashData) {
24
+ const bestVideo = getBest(dashData.video),
25
+ bestAudio = getBest(dashData.audio);
26
+
27
+ if (!bestVideo || !bestAudio) return [];
28
+ return [ bestVideo, bestAudio ];
29
+ }
30
+
31
+ async function com_download(id) {
32
+ let html = await fetch(`https://bilibili.com/video/${id}`, {
33
+ headers: {
34
+ "user-agent": genericUserAgent
35
+ }
36
+ })
37
+ .then(r => r.text())
38
+ .catch(() => {});
39
+
40
+ if (!html) {
41
+ return { error: "fetch.fail" }
42
+ }
43
+
44
+ if (!(html.includes('<script>window.__playinfo__=') && html.includes('"video_codecid"'))) {
45
+ return { error: "fetch.empty" };
46
+ }
47
+
48
+ let streamData = JSON.parse(html.split('<script>window.__playinfo__=')[1].split('</script>')[0]);
49
+ if (streamData.data.timelength > env.durationLimit * 1000) {
50
+ return { error: "content.too_long" };
51
+ }
52
+
53
+ const [ video, audio ] = extractBestQuality(streamData.data.dash);
54
+ if (!video || !audio) {
55
+ return { error: "fetch.empty" };
56
+ }
57
+
58
+ return {
59
+ urls: [video.baseUrl, audio.baseUrl],
60
+ audioFilename: `bilibili_${id}_audio`,
61
+ filename: `bilibili_${id}_${video.width}x${video.height}.mp4`
62
+ };
63
+ }
64
+
65
+ async function tv_download(id) {
66
+ const url = new URL(
67
+ 'https://api.bilibili.tv/intl/gateway/web/playurl'
68
+ + '?s_locale=en_US&platform=web&qn=64&type=0&device=wap'
69
+ + '&tf=0&spm_id=bstar-web.ugc-video-detail.0.0&from_spm_id='
70
+ );
71
+
72
+ url.searchParams.set('aid', id);
73
+
74
+ const { data } = await fetch(url).then(a => a.json());
75
+ if (!data?.playurl?.video) {
76
+ return { error: "fetch.empty" };
77
+ }
78
+
79
+ const [ video, audio ] = extractBestQuality({
80
+ video: data.playurl.video.map(s => s.video_resource)
81
+ .filter(s => s.codecs.includes('avc1')),
82
+ audio: data.playurl.audio_resource
83
+ });
84
+
85
+ if (!video || !audio) {
86
+ return { error: "fetch.empty" };
87
+ }
88
+
89
+ if (video.duration > env.durationLimit * 1000) {
90
+ return { error: "content.too_long" };
91
+ }
92
+
93
+ return {
94
+ urls: [video.url, audio.url],
95
+ audioFilename: `bilibili_tv_${id}_audio`,
96
+ filename: `bilibili_tv_${id}.mp4`
97
+ };
98
+ }
99
+
100
+ export default async function({ comId, tvId, comShortLink }) {
101
+ if (comShortLink) {
102
+ comId = await com_resolveShortlink(comShortLink);
103
+ }
104
+
105
+ if (comId) {
106
+ return com_download(comId);
107
+ } else if (tvId) {
108
+ return tv_download(tvId);
109
+ }
110
+
111
+ return { error: "fetch.fail" };
112
+ }
api/src/processing/services/bluesky.js ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import HLS from "hls-parser";
2
+ import { cobaltUserAgent } from "../../config.js";
3
+ import { createStream } from "../../stream/manage.js";
4
+
5
+ const extractVideo = async ({ media, filename }) => {
6
+ const urlMasterHLS = media?.playlist;
7
+ if (!urlMasterHLS) return { error: "fetch.empty" };
8
+ if (!urlMasterHLS.startsWith("https://video.bsky.app/")) return { error: "fetch.empty" };
9
+
10
+ const masterHLS = await fetch(urlMasterHLS)
11
+ .then(r => {
12
+ if (r.status !== 200) return;
13
+ return r.text();
14
+ })
15
+ .catch(() => {});
16
+
17
+ if (!masterHLS) return { error: "fetch.empty" };
18
+
19
+ const video = HLS.parse(masterHLS)
20
+ ?.variants
21
+ ?.reduce((a, b) => a?.bandwidth > b?.bandwidth ? a : b);
22
+
23
+ const videoURL = new URL(video.uri, urlMasterHLS).toString();
24
+
25
+ return {
26
+ urls: videoURL,
27
+ filename: `${filename}.mp4`,
28
+ audioFilename: `${filename}_audio`,
29
+ isM3U8: true,
30
+ }
31
+ }
32
+
33
+ const extractImages = ({ getPost, filename, alwaysProxy }) => {
34
+ const images = getPost?.thread?.post?.embed?.images;
35
+
36
+ if (!images || images.length === 0) {
37
+ return { error: "fetch.empty" };
38
+ }
39
+
40
+ if (images.length === 1) return {
41
+ urls: images[0].fullsize,
42
+ isPhoto: true,
43
+ filename: `${filename}.jpg`,
44
+ }
45
+
46
+ const picker = images.map((image, i) => {
47
+ let url = image.fullsize;
48
+ let proxiedImage = createStream({
49
+ service: "bluesky",
50
+ type: "proxy",
51
+ u: url,
52
+ filename: `${filename}_${i + 1}.jpg`,
53
+ });
54
+
55
+ if (alwaysProxy) url = proxiedImage;
56
+
57
+ return {
58
+ type: "photo",
59
+ url,
60
+ thumb: proxiedImage,
61
+ }
62
+ });
63
+
64
+ return { picker };
65
+ }
66
+
67
+ export default async function ({ user, post, alwaysProxy }) {
68
+ const apiEndpoint = new URL("https://public.api.bsky.app/xrpc/app.bsky.feed.getPostThread?depth=0&parentHeight=0");
69
+ apiEndpoint.searchParams.set(
70
+ "uri",
71
+ `at://${user}/app.bsky.feed.post/${post}`
72
+ );
73
+
74
+ const getPost = await fetch(apiEndpoint, {
75
+ headers: {
76
+ "user-agent": cobaltUserAgent
77
+ }
78
+ }).then(r => r.json()).catch(() => {});
79
+
80
+ if (!getPost) return { error: "fetch.empty" };
81
+
82
+ if (getPost.error) {
83
+ switch (getPost.error) {
84
+ case "NotFound":
85
+ case "InternalServerError":
86
+ return { error: "content.post.unavailable" };
87
+ case "InvalidRequest":
88
+ return { error: "link.unsupported" };
89
+ default:
90
+ return { error: "fetch.empty" };
91
+ }
92
+ }
93
+
94
+ const embedType = getPost?.thread?.post?.embed?.$type;
95
+ const filename = `bluesky_${user}_${post}`;
96
+
97
+ if (embedType === "app.bsky.embed.video#view") {
98
+ return extractVideo({
99
+ media: getPost.thread?.post?.embed,
100
+ filename,
101
+ })
102
+ }
103
+
104
+ if (embedType === "app.bsky.embed.recordWithMedia#view") {
105
+ return extractVideo({
106
+ media: getPost.thread?.post?.embed?.media,
107
+ filename,
108
+ })
109
+ }
110
+
111
+ if (embedType === "app.bsky.embed.images#view") {
112
+ return extractImages({ getPost, filename, alwaysProxy });
113
+ }
114
+
115
+ return { error: "fetch.empty" };
116
+ }
api/src/processing/services/dailymotion.js ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import HLSParser from "hls-parser";
2
+ import { env } from "../../config.js";
3
+
4
+ let _token;
5
+
6
+ function getExp(token) {
7
+ return JSON.parse(
8
+ Buffer.from(token.split('.')[1], 'base64')
9
+ ).exp * 1000;
10
+ }
11
+
12
+ const getToken = async () => {
13
+ if (_token && getExp(_token) > new Date().getTime()) {
14
+ return _token;
15
+ }
16
+
17
+ const req = await fetch('https://graphql.api.dailymotion.com/oauth/token', {
18
+ method: 'POST',
19
+ headers: {
20
+ 'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8',
21
+ 'User-Agent': 'dailymotion/240213162706 CFNetwork/1492.0.1 Darwin/23.3.0',
22
+ 'Authorization': 'Basic MGQyZDgyNjQwOWFmOWU3MmRiNWQ6ODcxNmJmYTVjYmEwMmUwMGJkYTVmYTg1NTliNDIwMzQ3NzIyYWMzYQ=='
23
+ },
24
+ body: 'traffic_segment=&grant_type=client_credentials'
25
+ }).then(r => r.json()).catch(() => {});
26
+
27
+ if (req.access_token) {
28
+ return _token = req.access_token;
29
+ }
30
+ }
31
+
32
+ export default async function({ id }) {
33
+ const token = await getToken();
34
+ if (!token) return { error: "fetch.fail" };
35
+
36
+ const req = await fetch('https://graphql.api.dailymotion.com/',
37
+ {
38
+ method: 'POST',
39
+ headers: {
40
+ 'User-Agent': 'dailymotion/240213162706 CFNetwork/1492.0.1 Darwin/23.3.0',
41
+ Authorization: `Bearer ${token}`,
42
+ 'Content-Type': 'application/json',
43
+ 'X-DM-AppInfo-Version': '7.16.0_240213162706',
44
+ 'X-DM-AppInfo-Type': 'iosapp',
45
+ 'X-DM-AppInfo-Id': 'com.dailymotion.dailymotion'
46
+ },
47
+ body: JSON.stringify({
48
+ operationName: "Media",
49
+ query: `
50
+ query Media($xid: String!, $password: String) {
51
+ media(xid: $xid, password: $password) {
52
+ __typename
53
+ ... on Video {
54
+ xid
55
+ hlsURL
56
+ duration
57
+ title
58
+ channel {
59
+ displayName
60
+ }
61
+ }
62
+ }
63
+ }
64
+ `,
65
+ variables: { xid: id }
66
+ })
67
+ }
68
+ ).then(r => r.status === 200 && r.json()).catch(() => {});
69
+
70
+ const media = req?.data?.media;
71
+
72
+ if (media?.__typename !== 'Video' || !media.hlsURL) {
73
+ return { error: "fetch.empty" }
74
+ }
75
+
76
+ if (media.duration > env.durationLimit) {
77
+ return { error: "content.too_long" };
78
+ }
79
+
80
+ const manifest = await fetch(media.hlsURL).then(r => r.text()).catch(() => {});
81
+ if (!manifest) return { error: "fetch.fail" };
82
+
83
+ const bestQuality = HLSParser.parse(manifest).variants
84
+ .filter(v => v.codecs.includes('avc1'))
85
+ .reduce((a, b) => a.bandwidth > b.bandwidth ? a : b);
86
+ if (!bestQuality) return { error: "fetch.empty" }
87
+
88
+ const fileMetadata = {
89
+ title: media.title,
90
+ artist: media.channel.displayName
91
+ }
92
+
93
+ return {
94
+ urls: bestQuality.uri,
95
+ isM3U8: true,
96
+ filenameAttributes: {
97
+ service: 'dailymotion',
98
+ id: media.xid,
99
+ title: fileMetadata.title,
100
+ author: fileMetadata.artist,
101
+ resolution: `${bestQuality.resolution.width}x${bestQuality.resolution.height}`,
102
+ qualityLabel: `${bestQuality.resolution.height}p`,
103
+ extension: 'mp4'
104
+ },
105
+ fileMetadata
106
+ }
107
+ }
api/src/processing/services/facebook.js ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { genericUserAgent } from "../../config.js";
2
+
3
+ const headers = {
4
+ 'User-Agent': genericUserAgent,
5
+ 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8',
6
+ 'Accept-Language': 'en-US,en;q=0.5',
7
+ 'Sec-Fetch-Mode': 'navigate',
8
+ 'Sec-Fetch-Site': 'none',
9
+ }
10
+
11
+ const resolveUrl = (url) => {
12
+ return fetch(url, { headers })
13
+ .then(r => {
14
+ if (r.headers.get('location')) {
15
+ return decodeURIComponent(r.headers.get('location'));
16
+ }
17
+ if (r.headers.get('link')) {
18
+ const linkMatch = r.headers.get('link').match(/<(.*?)\/>/);
19
+ return decodeURIComponent(linkMatch[1]);
20
+ }
21
+ return false;
22
+ })
23
+ .catch(() => false);
24
+ }
25
+
26
+ export default async function({ id, shareType, shortLink }) {
27
+ let url = `https://web.facebook.com/i/videos/${id}`;
28
+
29
+ if (shareType) url = `https://web.facebook.com/share/${shareType}/${id}`;
30
+ if (shortLink) url = await resolveUrl(`https://fb.watch/${shortLink}`);
31
+
32
+ const html = await fetch(url, { headers })
33
+ .then(r => r.text())
34
+ .catch(() => false);
35
+
36
+ if (!html && shortLink) return { error: "fetch.short_link" }
37
+ if (!html) return { error: "fetch.fail" };
38
+
39
+ const urls = [];
40
+ const hd = html.match('"browser_native_hd_url":(".*?")');
41
+ const sd = html.match('"browser_native_sd_url":(".*?")');
42
+
43
+ if (hd?.[1]) urls.push(JSON.parse(hd[1]));
44
+ if (sd?.[1]) urls.push(JSON.parse(sd[1]));
45
+
46
+ if (!urls.length) {
47
+ return { error: "fetch.empty" };
48
+ }
49
+
50
+ const baseFilename = `facebook_${id || shortLink}`;
51
+
52
+ return {
53
+ urls: urls[0],
54
+ filename: `${baseFilename}.mp4`,
55
+ audioFilename: `${baseFilename}_audio`,
56
+ };
57
+ }
api/src/processing/services/instagram.js ADDED
@@ -0,0 +1,372 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { genericUserAgent } from "../../config.js";
2
+ import { createStream } from "../../stream/manage.js";
3
+ import { getCookie, updateCookie } from "../cookie/manager.js";
4
+
5
+ const commonHeaders = {
6
+ "user-agent": genericUserAgent,
7
+ "sec-gpc": "1",
8
+ "sec-fetch-site": "same-origin",
9
+ "x-ig-app-id": "936619743392459"
10
+ }
11
+ const mobileHeaders = {
12
+ "x-ig-app-locale": "en_US",
13
+ "x-ig-device-locale": "en_US",
14
+ "x-ig-mapped-locale": "en_US",
15
+ "user-agent": "Instagram 275.0.0.27.98 Android (33/13; 280dpi; 720x1423; Xiaomi; Redmi 7; onclite; qcom; en_US; 458229237)",
16
+ "accept-language": "en-US",
17
+ "x-fb-http-engine": "Liger",
18
+ "x-fb-client-ip": "True",
19
+ "x-fb-server-cluster": "True",
20
+ "content-length": "0",
21
+ }
22
+ const embedHeaders = {
23
+ "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
24
+ "Accept-Language": "en-GB,en;q=0.9",
25
+ "Cache-Control": "max-age=0",
26
+ "Dnt": "1",
27
+ "Priority": "u=0, i",
28
+ "Sec-Ch-Ua": 'Chromium";v="124", "Google Chrome";v="124", "Not-A.Brand";v="99',
29
+ "Sec-Ch-Ua-Mobile": "?0",
30
+ "Sec-Ch-Ua-Platform": "macOS",
31
+ "Sec-Fetch-Dest": "document",
32
+ "Sec-Fetch-Mode": "navigate",
33
+ "Sec-Fetch-Site": "none",
34
+ "Sec-Fetch-User": "?1",
35
+ "Upgrade-Insecure-Requests": "1",
36
+ "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36",
37
+ }
38
+
39
+ const cachedDtsg = {
40
+ value: '',
41
+ expiry: 0
42
+ }
43
+
44
+ export default function(obj) {
45
+ const dispatcher = obj.dispatcher;
46
+
47
+ async function findDtsgId(cookie) {
48
+ try {
49
+ if (cachedDtsg.expiry > Date.now()) return cachedDtsg.value;
50
+
51
+ const data = await fetch('https://www.instagram.com/', {
52
+ headers: {
53
+ ...commonHeaders,
54
+ cookie
55
+ },
56
+ dispatcher
57
+ }).then(r => r.text());
58
+
59
+ const token = data.match(/"dtsg":{"token":"(.*?)"/)[1];
60
+
61
+ cachedDtsg.value = token;
62
+ cachedDtsg.expiry = Date.now() + 86390000;
63
+
64
+ if (token) return token;
65
+ return false;
66
+ }
67
+ catch {}
68
+ }
69
+
70
+ async function request(url, cookie, method = 'GET', requestData) {
71
+ let headers = {
72
+ ...commonHeaders,
73
+ 'x-ig-www-claim': cookie?._wwwClaim || '0',
74
+ 'x-csrftoken': cookie?.values()?.csrftoken,
75
+ cookie
76
+ }
77
+ if (method === 'POST') {
78
+ headers['content-type'] = 'application/x-www-form-urlencoded';
79
+ }
80
+
81
+ const data = await fetch(url, {
82
+ method,
83
+ headers,
84
+ body: requestData && new URLSearchParams(requestData),
85
+ dispatcher
86
+ });
87
+
88
+ if (data.headers.get('X-Ig-Set-Www-Claim') && cookie)
89
+ cookie._wwwClaim = data.headers.get('X-Ig-Set-Www-Claim');
90
+
91
+ updateCookie(cookie, data.headers);
92
+ return data.json();
93
+ }
94
+ async function getMediaId(id, { cookie, token } = {}) {
95
+ const oembedURL = new URL('https://i.instagram.com/api/v1/oembed/');
96
+ oembedURL.searchParams.set('url', `https://www.instagram.com/p/${id}/`);
97
+
98
+ const oembed = await fetch(oembedURL, {
99
+ headers: {
100
+ ...mobileHeaders,
101
+ ...( token && { authorization: `Bearer ${token}` } ),
102
+ cookie
103
+ },
104
+ dispatcher
105
+ }).then(r => r.json()).catch(() => {});
106
+
107
+ return oembed?.media_id;
108
+ }
109
+
110
+ async function requestMobileApi(mediaId, { cookie, token } = {}) {
111
+ const mediaInfo = await fetch(`https://i.instagram.com/api/v1/media/${mediaId}/info/`, {
112
+ headers: {
113
+ ...mobileHeaders,
114
+ ...( token && { authorization: `Bearer ${token}` } ),
115
+ cookie
116
+ },
117
+ dispatcher
118
+ }).then(r => r.json()).catch(() => {});
119
+
120
+ return mediaInfo?.items?.[0];
121
+ }
122
+ async function requestHTML(id, cookie) {
123
+ const data = await fetch(`https://www.instagram.com/p/${id}/embed/captioned/`, {
124
+ headers: {
125
+ ...embedHeaders,
126
+ cookie
127
+ },
128
+ dispatcher
129
+ }).then(r => r.text()).catch(() => {});
130
+
131
+ let embedData = JSON.parse(data?.match(/"init",\[\],\[(.*?)\]\],/)[1]);
132
+
133
+ if (!embedData || !embedData?.contextJSON) return false;
134
+
135
+ embedData = JSON.parse(embedData.contextJSON);
136
+
137
+ return embedData;
138
+ }
139
+ async function requestGQL(id, cookie) {
140
+ let dtsgId;
141
+
142
+ if (cookie) {
143
+ dtsgId = await findDtsgId(cookie);
144
+ }
145
+ const url = new URL('https://www.instagram.com/api/graphql/');
146
+
147
+ const requestData = {
148
+ jazoest: '26406',
149
+ variables: JSON.stringify({
150
+ shortcode: id,
151
+ __relay_internal__pv__PolarisShareMenurelayprovider: false
152
+ }),
153
+ doc_id: '7153618348081770'
154
+ };
155
+ if (dtsgId) {
156
+ requestData.fb_dtsg = dtsgId;
157
+ }
158
+
159
+ return (await request(url, cookie, 'POST', requestData))
160
+ .data
161
+ ?.xdt_api__v1__media__shortcode__web_info
162
+ ?.items
163
+ ?.[0];
164
+ }
165
+
166
+ function extractOldPost(data, id, alwaysProxy) {
167
+ const sidecar = data?.gql_data?.shortcode_media?.edge_sidecar_to_children;
168
+ if (sidecar) {
169
+ const picker = sidecar.edges.filter(e => e.node?.display_url)
170
+ .map((e, i) => {
171
+ const type = e.node?.is_video ? "video" : "photo";
172
+ const url = type === "video" ? e.node?.video_url : e.node?.display_url;
173
+
174
+ let itemExt = type === "video" ? "mp4" : "jpg";
175
+
176
+ let proxyFile;
177
+ if (alwaysProxy) proxyFile = createStream({
178
+ service: "instagram",
179
+ type: "proxy",
180
+ u: url,
181
+ filename: `instagram_${id}_${i + 1}.${itemExt}`
182
+ });
183
+
184
+ return {
185
+ type,
186
+ url: proxyFile || url,
187
+ /* thumbnails have `Cross-Origin-Resource-Policy`
188
+ ** set to `same-origin`, so we need to proxy them */
189
+ thumb: createStream({
190
+ service: "instagram",
191
+ type: "proxy",
192
+ u: e.node?.display_url,
193
+ filename: `instagram_${id}_${i + 1}.jpg`
194
+ })
195
+ }
196
+ });
197
+
198
+ if (picker.length) return { picker }
199
+ } else if (data?.gql_data?.shortcode_media?.video_url) {
200
+ return {
201
+ urls: data.gql_data.shortcode_media.video_url,
202
+ filename: `instagram_${id}.mp4`,
203
+ audioFilename: `instagram_${id}_audio`
204
+ }
205
+ } else if (data?.gql_data?.shortcode_media?.display_url) {
206
+ return {
207
+ urls: data.gql_data?.shortcode_media.display_url,
208
+ isPhoto: true
209
+ }
210
+ }
211
+ }
212
+
213
+ function extractNewPost(data, id, alwaysProxy) {
214
+ const carousel = data.carousel_media;
215
+ if (carousel) {
216
+ const picker = carousel.filter(e => e?.image_versions2)
217
+ .map((e, i) => {
218
+ const type = e.video_versions ? "video" : "photo";
219
+ const imageUrl = e.image_versions2.candidates[0].url;
220
+
221
+ let url = imageUrl;
222
+ let itemExt = type === "video" ? "mp4" : "jpg";
223
+
224
+ if (type === "video") {
225
+ const video = e.video_versions.reduce((a, b) => a.width * a.height < b.width * b.height ? b : a);
226
+ url = video.url;
227
+ }
228
+
229
+ let proxyFile;
230
+ if (alwaysProxy) proxyFile = createStream({
231
+ service: "instagram",
232
+ type: "proxy",
233
+ u: url,
234
+ filename: `instagram_${id}_${i + 1}.${itemExt}`
235
+ });
236
+
237
+ return {
238
+ type,
239
+ url: proxyFile || url,
240
+ /* thumbnails have `Cross-Origin-Resource-Policy`
241
+ ** set to `same-origin`, so we need to always proxy them */
242
+ thumb: createStream({
243
+ service: "instagram",
244
+ type: "proxy",
245
+ u: imageUrl,
246
+ filename: `instagram_${id}_${i + 1}.jpg`
247
+ })
248
+ }
249
+ });
250
+
251
+ if (picker.length) return { picker }
252
+ } else if (data.video_versions) {
253
+ const video = data.video_versions.reduce((a, b) => a.width * a.height < b.width * b.height ? b : a)
254
+ return {
255
+ urls: video.url,
256
+ filename: `instagram_${id}.mp4`,
257
+ audioFilename: `instagram_${id}_audio`
258
+ }
259
+ } else if (data.image_versions2?.candidates) {
260
+ return {
261
+ urls: data.image_versions2.candidates[0].url,
262
+ isPhoto: true,
263
+ filename: `instagram_${id}.jpg`,
264
+ }
265
+ }
266
+ }
267
+
268
+ async function getPost(id, alwaysProxy) {
269
+ let data, result;
270
+ try {
271
+ const cookie = getCookie('instagram');
272
+
273
+ const bearer = getCookie('instagram_bearer');
274
+ const token = bearer?.values()?.token;
275
+
276
+ // get media_id for mobile api, three methods
277
+ let media_id = await getMediaId(id);
278
+ if (!media_id && token) media_id = await getMediaId(id, { token });
279
+ if (!media_id && cookie) media_id = await getMediaId(id, { cookie });
280
+
281
+ // mobile api (bearer)
282
+ if (media_id && token) data = await requestMobileApi(media_id, { token });
283
+
284
+ // mobile api (no cookie, cookie)
285
+ if (media_id && !data) data = await requestMobileApi(media_id);
286
+ if (media_id && cookie && !data) data = await requestMobileApi(media_id, { cookie });
287
+
288
+ // html embed (no cookie, cookie)
289
+ if (!data) data = await requestHTML(id);
290
+ if (!data && cookie) data = await requestHTML(id, cookie);
291
+
292
+ // web app graphql api (no cookie, cookie)
293
+ if (!data) data = await requestGQL(id);
294
+ if (!data && cookie) data = await requestGQL(id, cookie);
295
+ } catch {}
296
+
297
+ if (!data) return { error: "fetch.fail" };
298
+
299
+ if (data?.gql_data) {
300
+ result = extractOldPost(data, id, alwaysProxy)
301
+ } else {
302
+ result = extractNewPost(data, id, alwaysProxy)
303
+ }
304
+
305
+ if (result) return result;
306
+ return { error: "fetch.empty" }
307
+ }
308
+
309
+ async function usernameToId(username, cookie) {
310
+ const url = new URL('https://www.instagram.com/api/v1/users/web_profile_info/');
311
+ url.searchParams.set('username', username);
312
+
313
+ try {
314
+ const data = await request(url, cookie);
315
+ return data?.data?.user?.id;
316
+ } catch {}
317
+ }
318
+
319
+ async function getStory(username, id) {
320
+ const cookie = getCookie('instagram');
321
+ if (!cookie) return { error: "link.unsupported" };
322
+
323
+ const userId = await usernameToId(username, cookie);
324
+ if (!userId) return { error: "fetch.empty" };
325
+
326
+ const dtsgId = await findDtsgId(cookie);
327
+
328
+ const url = new URL('https://www.instagram.com/api/graphql/');
329
+ const requestData = {
330
+ fb_dtsg: dtsgId,
331
+ jazoest: '26438',
332
+ variables: JSON.stringify({
333
+ reel_ids_arr : [ userId ],
334
+ }),
335
+ server_timestamps: true,
336
+ doc_id: '25317500907894419'
337
+ };
338
+
339
+ let media;
340
+ try {
341
+ const data = (await request(url, cookie, 'POST', requestData));
342
+ media = data?.data?.xdt_api__v1__feed__reels_media?.reels_media?.find(m => m.id === userId);
343
+ } catch {}
344
+
345
+ const item = media.items.find(m => m.pk === id);
346
+ if (!item) return { error: "fetch.empty" };
347
+
348
+ if (item.video_versions) {
349
+ const video = item.video_versions.reduce((a, b) => a.width * a.height < b.width * b.height ? b : a)
350
+ return {
351
+ urls: video.url,
352
+ filename: `instagram_${id}.mp4`,
353
+ audioFilename: `instagram_${id}_audio`
354
+ }
355
+ }
356
+
357
+ if (item.image_versions2?.candidates) {
358
+ return {
359
+ urls: item.image_versions2.candidates[0].url,
360
+ isPhoto: true
361
+ }
362
+ }
363
+
364
+ return { error: "link.unsupported" };
365
+ }
366
+
367
+ const { postId, storyId, username, alwaysProxy } = obj;
368
+ if (postId) return getPost(postId, alwaysProxy);
369
+ if (username && storyId) return getStory(username, storyId);
370
+
371
+ return { error: "fetch.empty" }
372
+ }
api/src/processing/services/loom.js ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { genericUserAgent } from "../../config.js";
2
+
3
+ export default async function({ id }) {
4
+ const gql = await fetch(`https://www.loom.com/api/campaigns/sessions/${id}/transcoded-url`, {
5
+ method: "POST",
6
+ headers: {
7
+ "user-agent": genericUserAgent,
8
+ origin: "https://www.loom.com",
9
+ referer: `https://www.loom.com/share/${id}`,
10
+ cookie: `loom_referral_video=${id};`,
11
+
12
+ "apollographql-client-name": "web",
13
+ "apollographql-client-version": "14c0b42",
14
+ "x-loom-request-source": "loom_web_14c0b42",
15
+ },
16
+ body: JSON.stringify({
17
+ force_original: false,
18
+ password: null,
19
+ anonID: null,
20
+ deviceID: null
21
+ })
22
+ })
23
+ .then(r => r.status === 200 ? r.json() : false)
24
+ .catch(() => {});
25
+
26
+ if (!gql) return { error: "fetch.empty" };
27
+
28
+ const videoUrl = gql?.url;
29
+
30
+ if (videoUrl?.includes('.mp4?')) {
31
+ return {
32
+ urls: videoUrl,
33
+ filename: `loom_${id}.mp4`,
34
+ audioFilename: `loom_${id}_audio`
35
+ }
36
+ }
37
+
38
+ return { error: "fetch.empty" }
39
+ }
api/src/processing/services/ok.js ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { genericUserAgent, env } from "../../config.js";
2
+ import { cleanString } from "../../misc/utils.js";
3
+
4
+ const resolutions = {
5
+ "ultra": "2160",
6
+ "quad": "1440",
7
+ "full": "1080",
8
+ "hd": "720",
9
+ "sd": "480",
10
+ "low": "360",
11
+ "lowest": "240",
12
+ "mobile": "144"
13
+ }
14
+
15
+ export default async function(o) {
16
+ let quality = o.quality === "max" ? "2160" : o.quality;
17
+
18
+ let html = await fetch(`https://ok.ru/video/${o.id}`, {
19
+ headers: { "user-agent": genericUserAgent }
20
+ }).then(r => r.text()).catch(() => {});
21
+
22
+ if (!html) return { error: "fetch.fail" };
23
+
24
+ let videoData = html.match(/<div data-module="OKVideo" .*? data-options="({.*?})"( .*?)>/)
25
+ ?.[1]
26
+ ?.replaceAll("&quot;", '"');
27
+
28
+ if (!videoData) {
29
+ return { error: "fetch.empty" };
30
+ }
31
+
32
+ videoData = JSON.parse(JSON.parse(videoData).flashvars.metadata);
33
+
34
+ if (videoData.provider !== "UPLOADED_ODKL")
35
+ return { error: "link.unsupported" };
36
+
37
+ if (videoData.movie.is_live)
38
+ return { error: "content.video.live" };
39
+
40
+ if (videoData.movie.duration > env.durationLimit)
41
+ return { error: "content.too_long" };
42
+
43
+ let videos = videoData.videos.filter(v => !v.disallowed);
44
+ let bestVideo = videos.find(v => resolutions[v.name] === quality) || videos[videos.length - 1];
45
+
46
+ let fileMetadata = {
47
+ title: cleanString(videoData.movie.title.trim()),
48
+ author: cleanString((videoData.author?.name || videoData.compilationTitle).trim()),
49
+ }
50
+
51
+ if (bestVideo) return {
52
+ urls: bestVideo.url,
53
+ filenameAttributes: {
54
+ service: "ok",
55
+ id: o.id,
56
+ title: fileMetadata.title,
57
+ author: fileMetadata.author,
58
+ resolution: `${resolutions[bestVideo.name]}p`,
59
+ qualityLabel: `${resolutions[bestVideo.name]}p`,
60
+ extension: "mp4"
61
+ }
62
+ }
63
+
64
+ return { error: "fetch.empty" }
65
+ }
api/src/processing/services/pinterest.js ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { genericUserAgent } from "../../config.js";
2
+
3
+ const videoRegex = /"url":"(https:\/\/v1\.pinimg\.com\/videos\/.*?)"/g;
4
+ const imageRegex = /src="(https:\/\/i\.pinimg\.com\/.*\.(jpg|gif))"/g;
5
+
6
+ export default async function(o) {
7
+ let id = o.id;
8
+
9
+ if (!o.id && o.shortLink) {
10
+ id = await fetch(`https://api.pinterest.com/url_shortener/${o.shortLink}/redirect/`, { redirect: "manual" })
11
+ .then(r => r.headers.get("location").split('pin/')[1].split('/')[0])
12
+ .catch(() => {});
13
+ }
14
+ if (id.includes("--")) id = id.split("--")[1];
15
+ if (!id) return { error: "fetch.fail" };
16
+
17
+ const html = await fetch(`https://www.pinterest.com/pin/${id}/`, {
18
+ headers: { "user-agent": genericUserAgent }
19
+ }).then(r => r.text()).catch(() => {});
20
+
21
+ if (!html) return { error: "fetch.fail" };
22
+
23
+ const videoLink = [...html.matchAll(videoRegex)]
24
+ .map(([, link]) => link)
25
+ .find(a => a.endsWith('.mp4') && a.includes('720p'));
26
+
27
+ if (videoLink) return {
28
+ urls: videoLink,
29
+ filename: `pinterest_${o.id}.mp4`,
30
+ audioFilename: `pinterest_${o.id}_audio`
31
+ }
32
+
33
+ const imageLink = [...html.matchAll(imageRegex)]
34
+ .map(([, link]) => link)
35
+ .find(a => a.endsWith('.jpg') || a.endsWith('.gif'));
36
+
37
+ const imageType = imageLink.endsWith(".gif") ? "gif" : "jpg"
38
+
39
+ if (imageLink) return {
40
+ urls: imageLink,
41
+ isPhoto: true,
42
+ filename: `pinterest_${o.id}.${imageType}`
43
+ }
44
+
45
+ return { error: "fetch.empty" };
46
+ }
api/src/processing/services/reddit.js ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { genericUserAgent, env } from "../../config.js";
2
+ import { getCookie, updateCookieValues } from "../cookie/manager.js";
3
+
4
+ async function getAccessToken() {
5
+ /* "cookie" in cookiefile needs to contain:
6
+ * client_id, client_secret, refresh_token
7
+ * e.g. client_id=bla; client_secret=bla; refresh_token=bla
8
+ *
9
+ * you can get these by making a reddit app and
10
+ * authenticating an account against reddit's oauth2 api
11
+ * see: https://github.com/reddit-archive/reddit/wiki/OAuth2
12
+ *
13
+ * any additional cookie fields are managed by this code and you
14
+ * should not touch them unless you know what you're doing. **/
15
+ const cookie = await getCookie('reddit');
16
+ if (!cookie) return;
17
+
18
+ const values = cookie.values(),
19
+ needRefresh = !values.access_token
20
+ || !values.expiry
21
+ || Number(values.expiry) < new Date().getTime();
22
+ if (!needRefresh) return values.access_token;
23
+
24
+ const data = await fetch('https://www.reddit.com/api/v1/access_token', {
25
+ method: 'POST',
26
+ headers: {
27
+ 'authorization': `Basic ${Buffer.from(
28
+ [values.client_id, values.client_secret].join(':')
29
+ ).toString('base64')}`,
30
+ 'content-type': 'application/x-www-form-urlencoded',
31
+ 'user-agent': genericUserAgent,
32
+ 'accept': 'application/json'
33
+ },
34
+ body: `grant_type=refresh_token&refresh_token=${encodeURIComponent(values.refresh_token)}`
35
+ }).then(r => r.json()).catch(() => {});
36
+ if (!data) return;
37
+
38
+ const { access_token, refresh_token, expires_in } = data;
39
+ if (!access_token) return;
40
+
41
+ updateCookieValues(cookie, {
42
+ ...cookie.values(),
43
+ access_token, refresh_token,
44
+ expiry: new Date().getTime() + (expires_in * 1000),
45
+ });
46
+
47
+ return access_token;
48
+ }
49
+
50
+ export default async function(obj) {
51
+ let url = new URL(`https://www.reddit.com/r/${obj.sub}/comments/${obj.id}.json`);
52
+
53
+ if (obj.user) {
54
+ url.pathname = `/user/${obj.user}/comments/${obj.id}.json`;
55
+ }
56
+
57
+ const accessToken = await getAccessToken();
58
+ if (accessToken) url.hostname = 'oauth.reddit.com';
59
+
60
+ let data = await fetch(
61
+ url, {
62
+ headers: {
63
+ 'User-Agent': genericUserAgent,
64
+ accept: 'application/json',
65
+ authorization: accessToken && `Bearer ${accessToken}`
66
+ }
67
+ }
68
+ ).then(r => r.json()).catch(() => {});
69
+
70
+ if (!data || !Array.isArray(data)) {
71
+ return { error: "fetch.fail" }
72
+ }
73
+
74
+ data = data[0]?.data?.children[0]?.data;
75
+
76
+ const id = `${String(obj.sub).toLowerCase()}_${obj.id}`;
77
+
78
+ if (data?.url?.endsWith('.gif')) return {
79
+ typeId: "redirect",
80
+ urls: data.url,
81
+ filename: `reddit_${id}.gif`,
82
+ }
83
+
84
+ if (!data.secure_media?.reddit_video)
85
+ return { error: "fetch.empty" };
86
+
87
+ if (data.secure_media?.reddit_video?.duration > env.durationLimit)
88
+ return { error: "content.too_long" };
89
+
90
+ let audio = false,
91
+ video = data.secure_media?.reddit_video?.fallback_url?.split('?')[0],
92
+ audioFileLink = `${data.secure_media?.reddit_video?.fallback_url?.split('DASH')[0]}audio`;
93
+
94
+ if (video.match('.mp4')) {
95
+ audioFileLink = `${video.split('_')[0]}_audio.mp4`
96
+ }
97
+
98
+ // test the existence of audio
99
+ await fetch(audioFileLink, { method: "HEAD" }).then(r => {
100
+ if (Number(r.status) === 200) {
101
+ audio = true
102
+ }
103
+ }).catch(() => {})
104
+
105
+ // fallback for videos with variable audio quality
106
+ if (!audio) {
107
+ audioFileLink = `${video.split('_')[0]}_AUDIO_128.mp4`
108
+ await fetch(audioFileLink, { method: "HEAD" }).then(r => {
109
+ if (Number(r.status) === 200) {
110
+ audio = true
111
+ }
112
+ }).catch(() => {})
113
+ }
114
+
115
+ if (!audio) return {
116
+ typeId: "redirect",
117
+ urls: video
118
+ }
119
+
120
+ return {
121
+ typeId: "tunnel",
122
+ type: "merge",
123
+ urls: [video, audioFileLink],
124
+ audioFilename: `reddit_${id}_audio`,
125
+ filename: `reddit_${id}.mp4`
126
+ }
127
+ }
api/src/processing/services/rutube.js ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import HLS from "hls-parser";
2
+
3
+ import { env } from "../../config.js";
4
+ import { cleanString } from "../../misc/utils.js";
5
+
6
+ async function requestJSON(url) {
7
+ try {
8
+ const r = await fetch(url);
9
+ return await r.json();
10
+ } catch {}
11
+ }
12
+
13
+ const delta = (a, b) => Math.abs(a - b);
14
+
15
+ export default async function(obj) {
16
+ if (obj.yappyId) {
17
+ const yappy = await requestJSON(
18
+ `https://rutube.ru/pangolin/api/web/yappy/yappypage/?client=wdp&videoId=${obj.yappyId}&page=1&page_size=15`
19
+ )
20
+ const yappyURL = yappy?.results?.find(r => r.id === obj.yappyId)?.link;
21
+ if (!yappyURL) return { error: "fetch.empty" };
22
+
23
+ return {
24
+ urls: yappyURL,
25
+ filename: `rutube_yappy_${obj.yappyId}.mp4`,
26
+ audioFilename: `rutube_yappy_${obj.yappyId}_audio`
27
+ }
28
+ }
29
+
30
+ const quality = Number(obj.quality) || 9000;
31
+
32
+ const requestURL = new URL(`https://rutube.ru/api/play/options/${obj.id}/?no_404=true&referer&pver=v2`);
33
+ if (obj.key) requestURL.searchParams.set('p', obj.key);
34
+
35
+ const play = await requestJSON(requestURL);
36
+ if (!play) return { error: "fetch.fail" };
37
+
38
+ if (play.detail || !play.video_balancer) return { error: "fetch.empty" };
39
+ if (play.live_streams?.hls) return { error: "content.video.live" };
40
+
41
+ if (play.duration > env.durationLimit * 1000)
42
+ return { error: "content.too_long" };
43
+
44
+ let m3u8 = await fetch(play.video_balancer.m3u8)
45
+ .then(r => r.text())
46
+ .catch(() => {});
47
+
48
+ if (!m3u8) return { error: "fetch.fail" };
49
+
50
+ m3u8 = HLS.parse(m3u8).variants;
51
+
52
+ const matchingQuality = m3u8.reduce((prev, next) => {
53
+ const diff = {
54
+ prev: delta(quality, prev.resolution.height),
55
+ next: delta(quality, next.resolution.height)
56
+ };
57
+
58
+ return diff.prev < diff.next ? prev : next;
59
+ });
60
+
61
+ const fileMetadata = {
62
+ title: cleanString(play.title.trim()),
63
+ artist: cleanString(play.author.name.trim()),
64
+ }
65
+
66
+ return {
67
+ urls: matchingQuality.uri,
68
+ isM3U8: true,
69
+ filenameAttributes: {
70
+ service: "rutube",
71
+ id: obj.id,
72
+ title: fileMetadata.title,
73
+ author: fileMetadata.artist,
74
+ resolution: `${matchingQuality.resolution.width}x${matchingQuality.resolution.height}`,
75
+ qualityLabel: `${matchingQuality.resolution.height}p`,
76
+ extension: "mp4"
77
+ },
78
+ fileMetadata: fileMetadata
79
+ }
80
+ }
api/src/processing/services/snapchat.js ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { extract, normalizeURL } from "../url.js";
2
+ import { genericUserAgent } from "../../config.js";
3
+ import { createStream } from "../../stream/manage.js";
4
+ import { getRedirectingURL } from "../../misc/utils.js";
5
+
6
+ const SPOTLIGHT_VIDEO_REGEX = /<link data-react-helmet="true" rel="preload" href="([^"]+)" as="video"\/>/;
7
+ const NEXT_DATA_REGEX = /<script id="__NEXT_DATA__" type="application\/json">({.+})<\/script><\/body><\/html>$/;
8
+
9
+ async function getSpotlight(id) {
10
+ const html = await fetch(`https://www.snapchat.com/spotlight/${id}`, {
11
+ headers: { 'user-agent': genericUserAgent }
12
+ }).then((r) => r.text()).catch(() => null);
13
+
14
+ if (!html) {
15
+ return { error: "fetch.fail" };
16
+ }
17
+
18
+ const videoURL = html.match(SPOTLIGHT_VIDEO_REGEX)?.[1];
19
+
20
+ if (videoURL && new URL(videoURL).hostname.endsWith(".sc-cdn.net")) {
21
+ return {
22
+ urls: videoURL,
23
+ filename: `snapchat_${id}.mp4`,
24
+ audioFilename: `snapchat_${id}_audio`
25
+ }
26
+ }
27
+ }
28
+
29
+ async function getStory(username, storyId, alwaysProxy) {
30
+ const html = await fetch(
31
+ `https://www.snapchat.com/add/${username}${storyId ? `/${storyId}` : ''}`,
32
+ { headers: { 'user-agent': genericUserAgent } }
33
+ )
34
+ .then((r) => r.text())
35
+ .catch(() => null);
36
+
37
+ if (!html) {
38
+ return { error: "fetch.fail" };
39
+ }
40
+
41
+ const nextDataString = html.match(NEXT_DATA_REGEX)?.[1];
42
+ if (nextDataString) {
43
+ const data = JSON.parse(nextDataString);
44
+ const storyIdParam = data.query.profileParams[1];
45
+
46
+ if (storyIdParam && data.props.pageProps.story) {
47
+ const story = data.props.pageProps.story.snapList.find((snap) => snap.snapId.value === storyIdParam);
48
+ if (story) {
49
+ if (story.snapMediaType === 0) {
50
+ return {
51
+ urls: story.snapUrls.mediaUrl,
52
+ filename: `snapchat_${storyId}.jpg`,
53
+ isPhoto: true
54
+ }
55
+ }
56
+
57
+ return {
58
+ urls: story.snapUrls.mediaUrl,
59
+ filename: `snapchat_${storyId}.mp4`,
60
+ audioFilename: `snapchat_${storyId}_audio`
61
+ }
62
+ }
63
+ }
64
+
65
+ const defaultStory = data.props.pageProps.curatedHighlights[0];
66
+ if (defaultStory) {
67
+ return {
68
+ picker: defaultStory.snapList.map(snap => {
69
+ const snapType = snap.snapMediaType === 0 ? "photo" : "video";
70
+ const snapExt = snapType === "video" ? "mp4" : "jpg";
71
+ let snapUrl = snap.snapUrls.mediaUrl;
72
+
73
+ const proxy = createStream({
74
+ service: "snapchat",
75
+ type: "proxy",
76
+ u: snapUrl,
77
+ filename: `snapchat_${username}_${snap.timestampInSec.value}.${snapExt}`,
78
+ });
79
+
80
+ let thumbProxy;
81
+ if (snapType === "video") thumbProxy = createStream({
82
+ service: "snapchat",
83
+ type: "proxy",
84
+ u: snap.snapUrls.mediaPreviewUrl.value,
85
+ });
86
+
87
+ if (alwaysProxy) snapUrl = proxy;
88
+
89
+ return {
90
+ type: snapType,
91
+ url: snapUrl,
92
+ thumb: thumbProxy || proxy,
93
+ }
94
+ })
95
+ }
96
+ }
97
+ }
98
+ }
99
+
100
+ export default async function (obj) {
101
+ let params = obj;
102
+ if (obj.shortLink) {
103
+ const link = await getRedirectingURL(`https://t.snapchat.com/${obj.shortLink}`);
104
+
105
+ if (!link?.startsWith('https://www.snapchat.com/')) {
106
+ return { error: "fetch.short_link" };
107
+ }
108
+
109
+ const extractResult = extract(normalizeURL(link));
110
+ if (extractResult?.host !== 'snapchat') {
111
+ return { error: "fetch.short_link" };
112
+ }
113
+
114
+ params = extractResult.patternMatch;
115
+ }
116
+
117
+ if (params.spotlightId) {
118
+ const result = await getSpotlight(params.spotlightId);
119
+ if (result) return result;
120
+ } else if (params.username) {
121
+ const result = await getStory(params.username, params.storyId, obj.alwaysProxy);
122
+ if (result) return result;
123
+ }
124
+
125
+ return { error: "fetch.fail" };
126
+ }
api/src/processing/services/soundcloud.js ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { env } from "../../config.js";
2
+ import { cleanString } from "../../misc/utils.js";
3
+
4
+ const cachedID = {
5
+ version: '',
6
+ id: ''
7
+ }
8
+
9
+ async function findClientID() {
10
+ try {
11
+ let sc = await fetch('https://soundcloud.com/').then(r => r.text()).catch(() => {});
12
+ let scVersion = String(sc.match(/<script>window\.__sc_version="[0-9]{10}"<\/script>/)[0].match(/[0-9]{10}/));
13
+
14
+ if (cachedID.version === scVersion) return cachedID.id;
15
+
16
+ let scripts = sc.matchAll(/<script.+src="(.+)">/g);
17
+ let clientid;
18
+ for (let script of scripts) {
19
+ let url = script[1];
20
+
21
+ if (!url?.startsWith('https://a-v2.sndcdn.com/')) {
22
+ return;
23
+ }
24
+
25
+ let scrf = await fetch(url).then(r => r.text()).catch(() => {});
26
+ let id = scrf.match(/\("client_id=[A-Za-z0-9]{32}"\)/);
27
+
28
+ if (id && typeof id[0] === 'string') {
29
+ clientid = id[0].match(/[A-Za-z0-9]{32}/)[0];
30
+ break;
31
+ }
32
+ }
33
+ cachedID.version = scVersion;
34
+ cachedID.id = clientid;
35
+
36
+ return clientid;
37
+ } catch {}
38
+ }
39
+
40
+ export default async function(obj) {
41
+ let clientId = await findClientID();
42
+ if (!clientId) return { error: "fetch.fail" };
43
+
44
+ let link;
45
+ if (obj.url.hostname === 'on.soundcloud.com' && obj.shortLink) {
46
+ link = await fetch(`https://on.soundcloud.com/${obj.shortLink}/`, { redirect: "manual" }).then(r => {
47
+ if (r.status === 302 && r.headers.get("location").startsWith("https://soundcloud.com/")) {
48
+ return r.headers.get("location").split('?', 1)[0]
49
+ }
50
+ }).catch(() => {});
51
+ }
52
+
53
+ if (!link && obj.author && obj.song) {
54
+ link = `https://soundcloud.com/${obj.author}/${obj.song}${obj.accessKey ? `/s-${obj.accessKey}` : ''}`
55
+ }
56
+
57
+ if (!link && obj.shortLink) return { error: "fetch.short_link" };
58
+ if (!link) return { error: "link.unsupported" };
59
+
60
+ let json = await fetch(`https://api-v2.soundcloud.com/resolve?url=${link}&client_id=${clientId}`)
61
+ .then(r => r.status === 200 ? r.json() : false)
62
+ .catch(() => {});
63
+
64
+ if (!json) return { error: "fetch.fail" };
65
+
66
+ if (!json.media.transcodings) return { error: "fetch.empty" };
67
+
68
+ let bestAudio = "opus",
69
+ selectedStream = json.media.transcodings.find(v => v.preset === "opus_0_0"),
70
+ mp3Media = json.media.transcodings.find(v => v.preset === "mp3_0_0");
71
+
72
+ // use mp3 if present if user prefers it or if opus isn't available
73
+ if (mp3Media && (obj.format === "mp3" || !selectedStream)) {
74
+ selectedStream = mp3Media;
75
+ bestAudio = "mp3"
76
+ }
77
+
78
+ let fileUrlBase = selectedStream.url;
79
+ let fileUrl = `${fileUrlBase}${fileUrlBase.includes("?") ? "&" : "?"}client_id=${clientId}&track_authorization=${json.track_authorization}`;
80
+
81
+ if (!fileUrl.startsWith("https://api-v2.soundcloud.com/media/soundcloud:tracks:"))
82
+ return { error: "fetch.empty" };
83
+
84
+ if (json.duration > env.durationLimit * 1000) {
85
+ return { error: "content.too_long" };
86
+ }
87
+
88
+ let file = await fetch(fileUrl)
89
+ .then(async r => (await r.json()).url)
90
+ .catch(() => {});
91
+ if (!file) return { error: "fetch.empty" };
92
+
93
+ let fileMetadata = {
94
+ title: cleanString(json.title.trim()),
95
+ artist: cleanString(json.user.username.trim()),
96
+ }
97
+
98
+ return {
99
+ urls: file,
100
+ filenameAttributes: {
101
+ service: "soundcloud",
102
+ id: json.id,
103
+ title: fileMetadata.title,
104
+ author: fileMetadata.artist
105
+ },
106
+ bestAudio,
107
+ fileMetadata
108
+ }
109
+ }
api/src/processing/services/streamable.js ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ export default async function(obj) {
2
+ let video = await fetch(`https://api.streamable.com/videos/${obj.id}`)
3
+ .then(r => r.status === 200 ? r.json() : false)
4
+ .catch(() => {});
5
+
6
+ if (!video) return { error: "fetch.empty" };
7
+
8
+ let best = video.files["mp4-mobile"];
9
+ if (video.files.mp4 && (obj.isAudioOnly || obj.quality === "max" || obj.quality >= 720)) {
10
+ best = video.files.mp4;
11
+ }
12
+
13
+ if (best) return {
14
+ urls: best.url,
15
+ filename: `streamable_${obj.id}_${best.width}x${best.height}.mp4`,
16
+ audioFilename: `streamable_${obj.id}_audio`,
17
+ fileMetadata: {
18
+ title: video.title
19
+ }
20
+ }
21
+ return { error: "fetch.fail" }
22
+ }
api/src/processing/services/tiktok.js ADDED
@@ -0,0 +1,134 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import Cookie from "../cookie/cookie.js";
2
+
3
+ import { extract } from "../url.js";
4
+ import { genericUserAgent } from "../../config.js";
5
+ import { updateCookie } from "../cookie/manager.js";
6
+ import { createStream } from "../../stream/manage.js";
7
+
8
+ const shortDomain = "https://vt.tiktok.com/";
9
+
10
+ export default async function(obj) {
11
+ const cookie = new Cookie({});
12
+ let postId = obj.postId;
13
+
14
+ if (!postId) {
15
+ let html = await fetch(`${shortDomain}${obj.id}`, {
16
+ redirect: "manual",
17
+ headers: {
18
+ "user-agent": genericUserAgent.split(' Chrome/1')[0]
19
+ }
20
+ }).then(r => r.text()).catch(() => {});
21
+
22
+ if (!html) return { error: "fetch.fail" };
23
+
24
+ if (html.startsWith('<a href="https://')) {
25
+ const extractedURL = html.split('<a href="')[1].split('?')[0];
26
+ const { patternMatch } = extract(extractedURL);
27
+ postId = patternMatch.postId
28
+ }
29
+ }
30
+ if (!postId) return { error: "fetch.short_link" };
31
+
32
+ // should always be /video/, even for photos
33
+ const res = await fetch(`https://tiktok.com/@i/video/${postId}`, {
34
+ headers: {
35
+ "user-agent": genericUserAgent,
36
+ cookie,
37
+ }
38
+ })
39
+ updateCookie(cookie, res.headers);
40
+
41
+ const html = await res.text();
42
+
43
+ let detail;
44
+ try {
45
+ const json = html
46
+ .split('<script id="__UNIVERSAL_DATA_FOR_REHYDRATION__" type="application/json">')[1]
47
+ .split('</script>')[0]
48
+ const data = JSON.parse(json)
49
+ detail = data["__DEFAULT_SCOPE__"]["webapp.video-detail"]["itemInfo"]["itemStruct"]
50
+ } catch {
51
+ return { error: "fetch.fail" };
52
+ }
53
+
54
+ let video, videoFilename, audioFilename, audio, images,
55
+ filenameBase = `tiktok_${detail.author.uniqueId}_${postId}`,
56
+ bestAudio; // will get defaulted to m4a later on in match-action
57
+
58
+ images = detail.imagePost?.images;
59
+
60
+ let playAddr = detail.video.playAddr;
61
+ if (obj.h265) {
62
+ const h265PlayAddr = detail?.video?.bitrateInfo?.find(b => b.CodecType.includes("h265"))?.PlayAddr.UrlList[0]
63
+ playAddr = h265PlayAddr || playAddr
64
+ }
65
+
66
+ if (!obj.isAudioOnly && !images) {
67
+ video = playAddr;
68
+ videoFilename = `${filenameBase}.mp4`;
69
+ } else {
70
+ audio = playAddr;
71
+ audioFilename = `${filenameBase}_audio`;
72
+
73
+ if (obj.fullAudio || !audio) {
74
+ audio = detail.music.playUrl;
75
+ audioFilename += `_original`
76
+ }
77
+ if (audio.includes("mime_type=audio_mpeg")) bestAudio = 'mp3';
78
+ }
79
+
80
+ if (video) {
81
+ return {
82
+ urls: video,
83
+ filename: videoFilename,
84
+ headers: { cookie }
85
+ }
86
+ }
87
+
88
+ if (images && obj.isAudioOnly) {
89
+ return {
90
+ urls: audio,
91
+ audioFilename: audioFilename,
92
+ isAudioOnly: true,
93
+ bestAudio,
94
+ headers: { cookie }
95
+ }
96
+ }
97
+
98
+ if (images) {
99
+ let imageLinks = images
100
+ .map(i => i.imageURL.urlList.find(p => p.includes(".jpeg?")))
101
+ .map((url, i) => {
102
+ if (obj.alwaysProxy) url = createStream({
103
+ service: "tiktok",
104
+ type: "proxy",
105
+ u: url,
106
+ filename: `${filenameBase}_photo_${i + 1}.jpg`
107
+ })
108
+
109
+ return {
110
+ type: "photo",
111
+ url
112
+ }
113
+ });
114
+
115
+ return {
116
+ picker: imageLinks,
117
+ urls: audio,
118
+ audioFilename: audioFilename,
119
+ isAudioOnly: true,
120
+ bestAudio,
121
+ headers: { cookie }
122
+ }
123
+ }
124
+
125
+ if (audio) {
126
+ return {
127
+ urls: audio,
128
+ audioFilename: audioFilename,
129
+ isAudioOnly: true,
130
+ bestAudio,
131
+ headers: { cookie }
132
+ }
133
+ }
134
+ }
api/src/processing/services/tumblr.js ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import psl from "psl";
2
+
3
+ const API_KEY = 'jrsCWX1XDuVxAFO4GkK147syAoN8BJZ5voz8tS80bPcj26Vc5Z';
4
+ const API_BASE = 'https://api-http2.tumblr.com';
5
+
6
+ function request(domain, id) {
7
+ const url = new URL(`/v2/blog/${domain}/posts/${id}/permalink`, API_BASE);
8
+ url.searchParams.set('api_key', API_KEY);
9
+ url.searchParams.set('fields[blogs]', 'uuid,name,avatar,?description,?can_message,?can_be_followed,?is_adult,?reply_conditions,'
10
+ + '?theme,?title,?url,?is_blocked_from_primary,?placement_id,?primary,?updated,?followed,'
11
+ + '?ask,?can_subscribe,?paywall_access,?subscription_plan,?is_blogless_advertiser,?tumblrmart_accessories');
12
+
13
+ return fetch(url, {
14
+ headers: {
15
+ 'User-Agent': 'Tumblr/iPhone/33.3/333010/17.3.1/tumblr',
16
+ 'X-Version': 'iPhone/33.3/333010/17.3.1/tumblr'
17
+ }
18
+ }).then(a => a.json()).catch(() => {});
19
+ }
20
+
21
+ export default async function(input) {
22
+ let { subdomain } = psl.parse(input.url.hostname);
23
+
24
+ if (subdomain?.includes('.')) {
25
+ return { error: "link.unsupported" };
26
+ } else if (subdomain === 'www' || subdomain === 'at') {
27
+ subdomain = undefined
28
+ }
29
+
30
+ const domain = `${subdomain ?? input.user}.tumblr.com`;
31
+ const data = await request(domain, input.id);
32
+
33
+ const element = data?.response?.timeline?.elements?.[0];
34
+ if (!element) return { error: "fetch.empty" };
35
+
36
+ const contents = [
37
+ ...element.content,
38
+ ...element?.trail?.map(t => t.content).flat()
39
+ ]
40
+
41
+ const audio = contents.find(c => c.type === 'audio');
42
+ if (audio && audio.provider === 'tumblr') {
43
+ const fileMetadata = {
44
+ title: audio?.title,
45
+ artist: audio?.artist
46
+ };
47
+
48
+ return {
49
+ urls: audio.media.url,
50
+ filenameAttributes: {
51
+ service: 'tumblr',
52
+ id: input.id,
53
+ title: fileMetadata.title,
54
+ author: fileMetadata.artist
55
+ },
56
+ isAudioOnly: true,
57
+ bestAudio: "mp3",
58
+ }
59
+ }
60
+
61
+ const video = contents.find(c => c.type === 'video');
62
+ if (video && video.provider === 'tumblr') {
63
+ return {
64
+ urls: video.media.url,
65
+ filename: `tumblr_${input.id}.mp4`,
66
+ audioFilename: `tumblr_${input.id}_audio`
67
+ }
68
+ }
69
+
70
+ return { error: "link.unsupported" }
71
+ }
api/src/processing/services/twitch.js ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { env } from "../../config.js";
2
+ import { cleanString } from '../../misc/utils.js';
3
+
4
+ const gqlURL = "https://gql.twitch.tv/gql";
5
+ const clientIdHead = { "client-id": "kimne78kx3ncx6brgo4mv6wki5h1ko" };
6
+
7
+ export default async function (obj) {
8
+ const req_metadata = await fetch(gqlURL, {
9
+ method: "POST",
10
+ headers: clientIdHead,
11
+ body: JSON.stringify({
12
+ query: `{
13
+ clip(slug: "${obj.clipId}") {
14
+ broadcaster {
15
+ login
16
+ }
17
+ createdAt
18
+ curator {
19
+ login
20
+ }
21
+ durationSeconds
22
+ id
23
+ medium: thumbnailURL(width: 480, height: 272)
24
+ title
25
+ videoQualities {
26
+ quality
27
+ sourceURL
28
+ }
29
+ }
30
+ }`
31
+ })
32
+ }).then(r => r.status === 200 ? r.json() : false).catch(() => {});
33
+
34
+ if (!req_metadata) return { error: "fetch.fail" };
35
+
36
+ const clipMetadata = req_metadata.data.clip;
37
+
38
+ if (clipMetadata.durationSeconds > env.durationLimit) {
39
+ return { error: "content.too_long" };
40
+ }
41
+ if (!clipMetadata.videoQualities || !clipMetadata.broadcaster) {
42
+ return { error: "fetch.empty" };
43
+ }
44
+
45
+ const req_token = await fetch(gqlURL, {
46
+ method: "POST",
47
+ headers: clientIdHead,
48
+ body: JSON.stringify([
49
+ {
50
+ "operationName": "VideoAccessToken_Clip",
51
+ "variables": {
52
+ "slug": obj.clipId
53
+ },
54
+ "extensions": {
55
+ "persistedQuery": {
56
+ "version": 1,
57
+ "sha256Hash": "36b89d2507fce29e5ca551df756d27c1cfe079e2609642b4390aa4c35796eb11"
58
+ }
59
+ }
60
+ }
61
+ ])
62
+ }).then(r => r.status === 200 ? r.json() : false).catch(() => {});
63
+
64
+ if (!req_token) return { error: "fetch.fail" };
65
+
66
+ const formats = clipMetadata.videoQualities;
67
+ const format = formats.find(f => f.quality === obj.quality) || formats[0];
68
+
69
+ return {
70
+ type: "proxy",
71
+ urls: `${format.sourceURL}?${new URLSearchParams({
72
+ sig: req_token[0].data.clip.playbackAccessToken.signature,
73
+ token: req_token[0].data.clip.playbackAccessToken.value
74
+ })}`,
75
+ fileMetadata: {
76
+ title: cleanString(clipMetadata.title.trim()),
77
+ artist: `Twitch Clip by @${clipMetadata.broadcaster.login}, clipped by @${clipMetadata.curator.login}`,
78
+ },
79
+ filenameAttributes: {
80
+ service: "twitch",
81
+ id: clipMetadata.id,
82
+ title: cleanString(clipMetadata.title.trim()),
83
+ author: `${clipMetadata.broadcaster.login}, clipped by ${clipMetadata.curator.login}`,
84
+ qualityLabel: `${format.quality}p`,
85
+ extension: 'mp4'
86
+ },
87
+ filename: `twitchclip_${clipMetadata.id}_${format.quality}p.mp4`,
88
+ audioFilename: `twitchclip_${clipMetadata.id}_audio`
89
+ }
90
+ }
api/src/processing/services/twitter.js ADDED
@@ -0,0 +1,235 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { genericUserAgent } from "../../config.js";
2
+ import { createStream } from "../../stream/manage.js";
3
+ import { getCookie, updateCookie } from "../cookie/manager.js";
4
+
5
+ const graphqlURL = 'https://api.x.com/graphql/I9GDzyCGZL2wSoYFFrrTVw/TweetResultByRestId';
6
+ const tokenURL = 'https://api.x.com/1.1/guest/activate.json';
7
+
8
+ const tweetFeatures = JSON.stringify({"creator_subscriptions_tweet_preview_api_enabled":true,"communities_web_enable_tweet_community_results_fetch":true,"c9s_tweet_anatomy_moderator_badge_enabled":true,"articles_preview_enabled":true,"tweetypie_unmention_optimization_enabled":true,"responsive_web_edit_tweet_api_enabled":true,"graphql_is_translatable_rweb_tweet_is_translatable_enabled":true,"view_counts_everywhere_api_enabled":true,"longform_notetweets_consumption_enabled":true,"responsive_web_twitter_article_tweet_consumption_enabled":true,"tweet_awards_web_tipping_enabled":false,"creator_subscriptions_quote_tweet_preview_enabled":false,"freedom_of_speech_not_reach_fetch_enabled":true,"standardized_nudges_misinfo":true,"tweet_with_visibility_results_prefer_gql_limited_actions_policy_enabled":true,"rweb_video_timestamps_enabled":true,"longform_notetweets_rich_text_read_enabled":true,"longform_notetweets_inline_media_enabled":true,"rweb_tipjar_consumption_enabled":true,"responsive_web_graphql_exclude_directive_enabled":true,"verified_phone_label_enabled":false,"responsive_web_graphql_skip_user_profile_image_extensions_enabled":false,"responsive_web_graphql_timeline_navigation_enabled":true,"responsive_web_enhance_cards_enabled":false});
9
+
10
+ const tweetFieldToggles = JSON.stringify({"withArticleRichContentState":true,"withArticlePlainText":false,"withGrokAnalyze":false});
11
+
12
+ const commonHeaders = {
13
+ "user-agent": genericUserAgent,
14
+ "authorization": "Bearer AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs%3D1Zv7ttfk8LF81IUq16cHjhLTvJu4FA33AGWWjCpTnA",
15
+ "x-twitter-client-language": "en",
16
+ "x-twitter-active-user": "yes",
17
+ "accept-language": "en"
18
+ }
19
+
20
+ // fix all videos affected by the container bug in twitter muxer (took them over two weeks to fix it????)
21
+ const TWITTER_EPOCH = 1288834974657n;
22
+ const badContainerStart = new Date(1701446400000);
23
+ const badContainerEnd = new Date(1702605600000);
24
+
25
+ function needsFixing(media) {
26
+ const representativeId = media.source_status_id_str ?? media.id_str;
27
+ const mediaTimestamp = new Date(
28
+ Number((BigInt(representativeId) >> 22n) + TWITTER_EPOCH)
29
+ );
30
+ return mediaTimestamp > badContainerStart && mediaTimestamp < badContainerEnd
31
+ }
32
+
33
+ function bestQuality(arr) {
34
+ return arr.filter(v => v.content_type === "video/mp4")
35
+ .reduce((a, b) => Number(a?.bitrate) > Number(b?.bitrate) ? a : b)
36
+ .url
37
+ }
38
+
39
+ let _cachedToken;
40
+ const getGuestToken = async (dispatcher, forceReload = false) => {
41
+ if (_cachedToken && !forceReload) {
42
+ return _cachedToken;
43
+ }
44
+
45
+ const tokenResponse = await fetch(tokenURL, {
46
+ method: 'POST',
47
+ headers: commonHeaders,
48
+ dispatcher
49
+ }).then(r => r.status === 200 && r.json()).catch(() => {})
50
+
51
+ if (tokenResponse?.guest_token) {
52
+ return _cachedToken = tokenResponse.guest_token
53
+ }
54
+ }
55
+
56
+ const requestTweet = async(dispatcher, tweetId, token, cookie) => {
57
+ const graphqlTweetURL = new URL(graphqlURL);
58
+
59
+ let headers = {
60
+ ...commonHeaders,
61
+ 'content-type': 'application/json',
62
+ 'x-guest-token': token,
63
+ cookie: `guest_id=${encodeURIComponent(`v1:${token}`)}`
64
+ }
65
+
66
+ if (cookie) {
67
+ headers = {
68
+ ...commonHeaders,
69
+ 'content-type': 'application/json',
70
+ 'X-Twitter-Auth-Type': 'OAuth2Session',
71
+ 'x-csrf-token': cookie.values().ct0,
72
+ cookie
73
+ }
74
+ }
75
+
76
+ graphqlTweetURL.searchParams.set('variables',
77
+ JSON.stringify({
78
+ tweetId,
79
+ withCommunity: false,
80
+ includePromotedContent: false,
81
+ withVoice: false
82
+ })
83
+ );
84
+ graphqlTweetURL.searchParams.set('features', tweetFeatures);
85
+ graphqlTweetURL.searchParams.set('fieldToggles', tweetFieldToggles);
86
+
87
+ let result = await fetch(graphqlTweetURL, { headers, dispatcher });
88
+ updateCookie(cookie, result.headers);
89
+
90
+ // we might have been missing the `ct0` cookie, retry
91
+ if (result.status === 403 && result.headers.get('set-cookie')) {
92
+ result = await fetch(graphqlTweetURL, {
93
+ headers: {
94
+ ...headers,
95
+ 'x-csrf-token': cookie.values().ct0
96
+ },
97
+ dispatcher
98
+ });
99
+ }
100
+
101
+ return result
102
+ }
103
+
104
+ export default async function({ id, index, toGif, dispatcher, alwaysProxy }) {
105
+ const cookie = await getCookie('twitter');
106
+
107
+ let guestToken = await getGuestToken(dispatcher);
108
+ if (!guestToken) return { error: "fetch.fail" };
109
+
110
+ let tweet = await requestTweet(dispatcher, id, guestToken);
111
+
112
+ // get new token & retry if old one expired
113
+ if ([403, 429].includes(tweet.status)) {
114
+ guestToken = await getGuestToken(dispatcher, true);
115
+ tweet = await requestTweet(dispatcher, id, guestToken)
116
+ }
117
+
118
+ tweet = await tweet.json();
119
+
120
+ let tweetTypename = tweet?.data?.tweetResult?.result?.__typename;
121
+
122
+ if (!tweetTypename) {
123
+ return { error: "fetch.empty" }
124
+ }
125
+
126
+ if (tweetTypename === "TweetUnavailable") {
127
+ const reason = tweet?.data?.tweetResult?.result?.reason;
128
+ switch(reason) {
129
+ case "Protected":
130
+ return { error: "content.post.private" }
131
+ case "NsfwLoggedOut":
132
+ if (cookie) {
133
+ tweet = await requestTweet(dispatcher, id, guestToken, cookie);
134
+ tweet = await tweet.json();
135
+ tweetTypename = tweet?.data?.tweetResult?.result?.__typename;
136
+ } else return { error: "content.post.age" }
137
+ }
138
+ }
139
+
140
+ if (!["Tweet", "TweetWithVisibilityResults"].includes(tweetTypename)) {
141
+ return { error: "content.post.unavailable" }
142
+ }
143
+
144
+ let tweetResult = tweet.data.tweetResult.result,
145
+ baseTweet = tweetResult.legacy,
146
+ repostedTweet = baseTweet?.retweeted_status_result?.result.legacy.extended_entities;
147
+
148
+ if (tweetTypename === "TweetWithVisibilityResults") {
149
+ baseTweet = tweetResult.tweet.legacy;
150
+ repostedTweet = baseTweet?.retweeted_status_result?.result.tweet.legacy.extended_entities;
151
+ }
152
+
153
+ let media = (repostedTweet?.media || baseTweet?.extended_entities?.media);
154
+
155
+ // check if there's a video at given index (/video/<index>)
156
+ if (index >= 0 && index < media?.length) {
157
+ media = [media[index]]
158
+ }
159
+
160
+ const getFileExt = (url) => new URL(url).pathname.split(".", 2)[1];
161
+
162
+ const proxyMedia = (u, filename) => createStream({
163
+ service: "twitter",
164
+ type: "proxy",
165
+ u, filename,
166
+ })
167
+
168
+ switch (media?.length) {
169
+ case undefined:
170
+ case 0:
171
+ return {
172
+ error: "fetch.empty"
173
+ }
174
+ case 1:
175
+ if (media[0].type === "photo") {
176
+ return {
177
+ type: "proxy",
178
+ isPhoto: true,
179
+ filename: `twitter_${id}.${getFileExt(media[0].media_url_https)}`,
180
+ urls: `${media[0].media_url_https}?name=4096x4096`
181
+ }
182
+ }
183
+
184
+ return {
185
+ type: needsFixing(media[0]) ? "remux" : "proxy",
186
+ urls: bestQuality(media[0].video_info.variants),
187
+ filename: `twitter_${id}.mp4`,
188
+ audioFilename: `twitter_${id}_audio`,
189
+ isGif: media[0].type === "animated_gif"
190
+ }
191
+ default:
192
+ const proxyThumb = (url, i) =>
193
+ proxyMedia(url, `twitter_${id}_${i + 1}.${getFileExt(url)}`);
194
+
195
+ const picker = media.map((content, i) => {
196
+ if (content.type === "photo") {
197
+ let url = `${content.media_url_https}?name=4096x4096`;
198
+ let proxiedImage = proxyThumb(url, i);
199
+
200
+ if (alwaysProxy) url = proxiedImage;
201
+
202
+ return {
203
+ type: "photo",
204
+ url,
205
+ thumb: proxiedImage,
206
+ }
207
+ }
208
+
209
+ let url = bestQuality(content.video_info.variants);
210
+ const shouldRenderGif = content.type === "animated_gif" && toGif;
211
+ const videoFilename = `twitter_${id}_${i + 1}.mp4`;
212
+
213
+ let type = "video";
214
+ if (shouldRenderGif) type = "gif";
215
+
216
+ if (needsFixing(content) || shouldRenderGif) {
217
+ url = createStream({
218
+ service: "twitter",
219
+ type: shouldRenderGif ? "gif" : "remux",
220
+ u: url,
221
+ filename: videoFilename,
222
+ })
223
+ } else if (alwaysProxy) {
224
+ url = proxyMedia(url, videoFilename);
225
+ }
226
+
227
+ return {
228
+ type,
229
+ url,
230
+ thumb: proxyThumb(content.media_url_https, i),
231
+ }
232
+ });
233
+ return { picker };
234
+ }
235
+ }
api/src/processing/services/vimeo.js ADDED
@@ -0,0 +1,171 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import HLS from "hls-parser";
2
+
3
+ import { env } from "../../config.js";
4
+ import { cleanString, merge } from '../../misc/utils.js';
5
+
6
+ const resolutionMatch = {
7
+ "3840": 2160,
8
+ "2732": 1440,
9
+ "2560": 1440,
10
+ "2048": 1080,
11
+ "1920": 1080,
12
+ "1366": 720,
13
+ "1280": 720,
14
+ "960": 480,
15
+ "640": 360,
16
+ "426": 240
17
+ }
18
+
19
+ const requestApiInfo = (videoId, password) => {
20
+ if (password) {
21
+ videoId += `:${password}`
22
+ }
23
+
24
+ return fetch(
25
+ `https://api.vimeo.com/videos/${videoId}`,
26
+ {
27
+ headers: {
28
+ Accept: 'application/vnd.vimeo.*+json; version=3.4.2',
29
+ 'User-Agent': 'Vimeo/10.19.0 (com.vimeo; build:101900.57.0; iOS 17.5.1) Alamofire/5.9.0 VimeoNetworking/5.0.0',
30
+ Authorization: 'Basic MTMxNzViY2Y0NDE0YTQ5YzhjZTc0YmU0NjVjNDQxYzNkYWVjOWRlOTpHKzRvMmgzVUh4UkxjdU5FRW80cDNDbDhDWGR5dVJLNUJZZ055dHBHTTB4V1VzaG41bEx1a2hiN0NWYWNUcldSSW53dzRUdFRYZlJEZmFoTTArOTBUZkJHS3R4V2llYU04Qnl1bERSWWxUdXRidjNqR2J4SHFpVmtFSUcyRktuQw==',
31
+ 'Accept-Language': 'en'
32
+ }
33
+ }
34
+ )
35
+ .then(a => a.json())
36
+ .catch(() => {});
37
+ }
38
+
39
+ const compareQuality = (rendition, requestedQuality) => {
40
+ const quality = parseInt(rendition);
41
+ return Math.abs(quality - requestedQuality);
42
+ }
43
+
44
+ const getDirectLink = (data, quality) => {
45
+ if (!data.files) return;
46
+
47
+ const match = data.files
48
+ .filter(f => f.rendition?.endsWith('p'))
49
+ .reduce((prev, next) => {
50
+ const delta = {
51
+ prev: compareQuality(prev.rendition, quality),
52
+ next: compareQuality(next.rendition, quality)
53
+ };
54
+
55
+ return delta.prev < delta.next ? prev : next;
56
+ });
57
+
58
+ if (!match) return;
59
+
60
+ return {
61
+ urls: match.link,
62
+ filenameAttributes: {
63
+ resolution: `${match.width}x${match.height}`,
64
+ qualityLabel: match.rendition,
65
+ extension: "mp4"
66
+ },
67
+ bestAudio: "mp3",
68
+ }
69
+ }
70
+
71
+ const getHLS = async (configURL, obj) => {
72
+ if (!configURL) return;
73
+
74
+ const api = await fetch(configURL)
75
+ .then(r => r.json())
76
+ .catch(() => {});
77
+ if (!api) return { error: "fetch.fail" };
78
+
79
+ if (api.video?.duration > env.durationLimit) {
80
+ return { error: "content.too_long" };
81
+ }
82
+
83
+ const urlMasterHLS = api.request?.files?.hls?.cdns?.akfire_interconnect_quic?.url;
84
+ if (!urlMasterHLS) return { error: "fetch.fail" };
85
+
86
+ const masterHLS = await fetch(urlMasterHLS)
87
+ .then(r => r.text())
88
+ .catch(() => {});
89
+
90
+ if (!masterHLS) return { error: "fetch.fail" };
91
+
92
+ const variants = HLS.parse(masterHLS)?.variants?.sort(
93
+ (a, b) => Number(b.bandwidth) - Number(a.bandwidth)
94
+ );
95
+ if (!variants || variants.length === 0) return { error: "fetch.empty" };
96
+
97
+ let bestQuality;
98
+
99
+ if (obj.quality < resolutionMatch[variants[0]?.resolution?.width]) {
100
+ bestQuality = variants.find(v =>
101
+ (obj.quality === resolutionMatch[v.resolution.width])
102
+ );
103
+ }
104
+
105
+ if (!bestQuality) bestQuality = variants[0];
106
+
107
+ const expandLink = (path) => {
108
+ return new URL(path, urlMasterHLS).toString();
109
+ };
110
+
111
+ let urls = expandLink(bestQuality.uri);
112
+
113
+ const audioPath = bestQuality?.audio[0]?.uri;
114
+ if (audioPath) {
115
+ urls = [
116
+ urls,
117
+ expandLink(audioPath)
118
+ ]
119
+ } else if (obj.isAudioOnly) {
120
+ return { error: "fetch.empty" };
121
+ }
122
+
123
+ return {
124
+ urls,
125
+ isM3U8: true,
126
+ filenameAttributes: {
127
+ resolution: `${bestQuality.resolution.width}x${bestQuality.resolution.height}`,
128
+ qualityLabel: `${resolutionMatch[bestQuality.resolution.width]}p`,
129
+ extension: "mp4"
130
+ },
131
+ bestAudio: "mp3",
132
+ }
133
+ }
134
+
135
+ export default async function(obj) {
136
+ let quality = obj.quality === "max" ? 9000 : Number(obj.quality);
137
+ if (quality < 240) quality = 240;
138
+ if (!quality || obj.isAudioOnly) quality = 9000;
139
+
140
+ const info = await requestApiInfo(obj.id, obj.password);
141
+ let response;
142
+
143
+ if (obj.isAudioOnly) {
144
+ response = await getHLS(info.config_url, { ...obj, quality });
145
+ }
146
+
147
+ if (!response) response = getDirectLink(info, quality);
148
+ if (!response) response = { error: "fetch.empty" };
149
+
150
+ if (response.error) {
151
+ return response;
152
+ }
153
+
154
+ const fileMetadata = {
155
+ title: cleanString(info.name),
156
+ artist: cleanString(info.user.name),
157
+ };
158
+
159
+ return merge(
160
+ {
161
+ fileMetadata,
162
+ filenameAttributes: {
163
+ service: "vimeo",
164
+ id: obj.id,
165
+ title: fileMetadata.title,
166
+ author: fileMetadata.artist,
167
+ }
168
+ },
169
+ response
170
+ );
171
+ }
api/src/processing/services/vine.js ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ export default async function(obj) {
2
+ let post = await fetch(`https://archive.vine.co/posts/${obj.id}.json`)
3
+ .then(r => r.json())
4
+ .catch(() => {});
5
+
6
+ if (!post) return { error: "fetch.empty" };
7
+
8
+ if (post.videoUrl) return {
9
+ urls: post.videoUrl.replace("http://", "https://"),
10
+ filename: `vine_${obj.id}.mp4`,
11
+ audioFilename: `vine_${obj.id}_audio`
12
+ }
13
+
14
+ return { error: "fetch.empty" }
15
+ }
api/src/processing/services/vk.js ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { cleanString } from "../../misc/utils.js";
2
+ import { genericUserAgent, env } from "../../config.js";
3
+
4
+ const resolutions = ["2160", "1440", "1080", "720", "480", "360", "240"];
5
+
6
+ export default async function(o) {
7
+ let html, url, quality = o.quality === "max" ? 2160 : o.quality;
8
+
9
+ html = await fetch(`https://vk.com/video${o.userId}_${o.videoId}`, {
10
+ headers: {
11
+ "user-agent": genericUserAgent
12
+ }
13
+ })
14
+ .then(r => r.arrayBuffer())
15
+ .catch(() => {});
16
+
17
+ if (!html) return { error: "fetch.fail" };
18
+
19
+ // decode cyrillic from windows-1251 because vk still uses apis from prehistoric times
20
+ let decoder = new TextDecoder('windows-1251');
21
+ html = decoder.decode(html);
22
+
23
+ if (!html.includes(`{"lang":`)) return { error: "fetch.empty" };
24
+
25
+ let js = JSON.parse('{"lang":' + html.split(`{"lang":`)[1].split(']);')[0]);
26
+
27
+ if (Number(js.mvData.is_active_live) !== 0) {
28
+ return { error: "content.video.live" };
29
+ }
30
+
31
+ if (js.mvData.duration > env.durationLimit) {
32
+ return { error: "content.too_long" };
33
+ }
34
+
35
+ for (let i in resolutions) {
36
+ if (js.player.params[0][`url${resolutions[i]}`]) {
37
+ quality = resolutions[i];
38
+ break
39
+ }
40
+ }
41
+ if (Number(quality) > Number(o.quality)) quality = o.quality;
42
+
43
+ url = js.player.params[0][`url${quality}`];
44
+
45
+ let fileMetadata = {
46
+ title: cleanString(js.player.params[0].md_title.trim()),
47
+ author: cleanString(js.player.params[0].md_author.trim()),
48
+ }
49
+
50
+ if (url) return {
51
+ urls: url,
52
+ filenameAttributes: {
53
+ service: "vk",
54
+ id: `${o.userId}_${o.videoId}`,
55
+ title: fileMetadata.title,
56
+ author: fileMetadata.author,
57
+ resolution: `${quality}p`,
58
+ qualityLabel: `${quality}p`,
59
+ extension: "mp4"
60
+ }
61
+ }
62
+ return { error: "fetch.empty" }
63
+ }
api/src/processing/services/youtube.js ADDED
@@ -0,0 +1,313 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { fetch } from "undici";
2
+
3
+ import { Innertube, Session } from "youtubei.js";
4
+
5
+ import { env } from "../../config.js";
6
+ import { cleanString } from "../../misc/utils.js";
7
+ import { getCookie, updateCookieValues } from "../cookie/manager.js";
8
+
9
+ const PLAYER_REFRESH_PERIOD = 1000 * 60 * 15; // ms
10
+
11
+ let innertube, lastRefreshedAt;
12
+
13
+ const codecMatch = {
14
+ h264: {
15
+ videoCodec: "avc1",
16
+ audioCodec: "mp4a",
17
+ container: "mp4"
18
+ },
19
+ av1: {
20
+ videoCodec: "av01",
21
+ audioCodec: "opus",
22
+ container: "webm"
23
+ },
24
+ vp9: {
25
+ videoCodec: "vp9",
26
+ audioCodec: "opus",
27
+ container: "webm"
28
+ }
29
+ }
30
+
31
+ const transformSessionData = (cookie) => {
32
+ if (!cookie)
33
+ return;
34
+
35
+ const values = { ...cookie.values() };
36
+ const REQUIRED_VALUES = [ 'access_token', 'refresh_token' ];
37
+
38
+ if (REQUIRED_VALUES.some(x => typeof values[x] !== 'string')) {
39
+ return;
40
+ }
41
+
42
+ if (values.expires) {
43
+ values.expiry_date = values.expires;
44
+ delete values.expires;
45
+ } else if (!values.expiry_date) {
46
+ return;
47
+ }
48
+
49
+ return values;
50
+ }
51
+
52
+ const cloneInnertube = async (customFetch) => {
53
+ const shouldRefreshPlayer = lastRefreshedAt + PLAYER_REFRESH_PERIOD < new Date();
54
+ if (!innertube || shouldRefreshPlayer) {
55
+ innertube = await Innertube.create({
56
+ fetch: customFetch
57
+ });
58
+ lastRefreshedAt = +new Date();
59
+ }
60
+
61
+ const session = new Session(
62
+ innertube.session.context,
63
+ innertube.session.key,
64
+ innertube.session.api_version,
65
+ innertube.session.account_index,
66
+ innertube.session.player,
67
+ undefined,
68
+ customFetch ?? innertube.session.http.fetch,
69
+ innertube.session.cache
70
+ );
71
+
72
+ const cookie = getCookie('youtube_oauth');
73
+ const oauthData = transformSessionData(cookie);
74
+
75
+ if (!session.logged_in && oauthData) {
76
+ await session.oauth.init(oauthData);
77
+ session.logged_in = true;
78
+ }
79
+
80
+ if (session.logged_in) {
81
+ if (session.oauth.shouldRefreshToken()) {
82
+ await session.oauth.refreshAccessToken();
83
+ }
84
+
85
+ const cookieValues = cookie.values();
86
+ const oldExpiry = new Date(cookieValues.expiry_date);
87
+ const newExpiry = new Date(session.oauth.oauth2_tokens.expiry_date);
88
+
89
+ if (oldExpiry.getTime() !== newExpiry.getTime()) {
90
+ updateCookieValues(cookie, {
91
+ ...session.oauth.client_id,
92
+ ...session.oauth.oauth2_tokens,
93
+ expiry_date: newExpiry.toISOString()
94
+ });
95
+ }
96
+ }
97
+
98
+ const yt = new Innertube(session);
99
+ return yt;
100
+ }
101
+
102
+ export default async function(o) {
103
+ let yt;
104
+ try {
105
+ yt = await cloneInnertube(
106
+ (input, init) => fetch(input, {
107
+ ...init,
108
+ dispatcher: o.dispatcher
109
+ })
110
+ );
111
+ } catch(e) {
112
+ if (e.message?.endsWith("decipher algorithm")) {
113
+ return { error: "youtube.decipher" }
114
+ } else if (e.message?.includes("refresh access token")) {
115
+ return { error: "youtube.token_expired" }
116
+ } else throw e;
117
+ }
118
+
119
+ const quality = o.quality === "max" ? "9000" : o.quality;
120
+
121
+ let info, isDubbed,
122
+ format = o.format || "h264";
123
+
124
+ function qual(i) {
125
+ if (!i.quality_label) {
126
+ return;
127
+ }
128
+
129
+ return i.quality_label.split('p')[0].split('s')[0]
130
+ }
131
+
132
+ try {
133
+ info = await yt.getBasicInfo(o.id, yt.session.logged_in ? 'ANDROID' : 'IOS');
134
+ } catch(e) {
135
+ if (e?.info?.reason === "This video is private") {
136
+ return { error: "content.video.private" };
137
+ } else if (e?.message === "This video is unavailable") {
138
+ return { error: "content.video.unavailable" };
139
+ } else {
140
+ return { error: "fetch.fail" };
141
+ }
142
+ }
143
+
144
+ if (!info) return { error: "fetch.fail" };
145
+
146
+ const playability = info.playability_status;
147
+ const basicInfo = info.basic_info;
148
+
149
+ if (playability.status === "LOGIN_REQUIRED") {
150
+ if (playability.reason.endsWith("bot")) {
151
+ return { error: "youtube.login" }
152
+ }
153
+ if (playability.reason.endsWith("age")) {
154
+ return { error: "content.video.age" }
155
+ }
156
+ if (playability?.error_screen?.reason?.text === "Private video") {
157
+ return { error: "content.video.private" }
158
+ }
159
+ }
160
+
161
+ if (playability.status === "UNPLAYABLE") {
162
+ if (playability?.reason?.endsWith("request limit.")) {
163
+ return { error: "fetch.rate" }
164
+ }
165
+ if (playability?.error_screen?.subreason?.text?.endsWith("in your country")) {
166
+ return { error: "content.video.region" }
167
+ }
168
+ if (playability?.error_screen?.reason?.text === "Private video") {
169
+ return { error: "content.video.private" }
170
+ }
171
+ }
172
+
173
+ if (playability.status !== "OK") {
174
+ return { error: "content.video.unavailable" };
175
+ }
176
+ if (basicInfo.is_live) {
177
+ return { error: "content.video.live" };
178
+ }
179
+
180
+ // return a critical error if returned video is "Video Not Available"
181
+ // or a similar stub by youtube
182
+ if (basicInfo.id !== o.id) {
183
+ return {
184
+ error: "fetch.fail",
185
+ critical: true
186
+ }
187
+ }
188
+
189
+ const filterByCodec = (formats) =>
190
+ formats
191
+ .filter(e =>
192
+ e.mime_type.includes(codecMatch[format].videoCodec)
193
+ || e.mime_type.includes(codecMatch[format].audioCodec)
194
+ )
195
+ .sort((a, b) => Number(b.bitrate) - Number(a.bitrate));
196
+
197
+ let adaptive_formats = filterByCodec(info.streaming_data.adaptive_formats);
198
+
199
+ if (adaptive_formats.length === 0 && format === "vp9") {
200
+ format = "h264"
201
+ adaptive_formats = filterByCodec(info.streaming_data.adaptive_formats)
202
+ }
203
+
204
+ let bestQuality;
205
+
206
+ const bestVideo = adaptive_formats.find(i => i.has_video && i.content_length);
207
+ const hasAudio = adaptive_formats.find(i => i.has_audio && i.content_length);
208
+
209
+ if (bestVideo) bestQuality = qual(bestVideo);
210
+
211
+ if ((!bestQuality && !o.isAudioOnly) || !hasAudio)
212
+ return { error: "youtube.codec" };
213
+
214
+ if (basicInfo.duration > env.durationLimit)
215
+ return { error: "content.too_long" };
216
+
217
+ const checkBestAudio = (i) => (i.has_audio && !i.has_video);
218
+
219
+ let audio = adaptive_formats.find(i =>
220
+ checkBestAudio(i) && i.is_original
221
+ );
222
+
223
+ if (o.dubLang) {
224
+ let dubbedAudio = adaptive_formats.find(i =>
225
+ checkBestAudio(i)
226
+ && i.language === o.dubLang
227
+ && i.audio_track
228
+ )
229
+
230
+ if (dubbedAudio && !dubbedAudio?.audio_track?.audio_is_default) {
231
+ audio = dubbedAudio;
232
+ isDubbed = true;
233
+ }
234
+ }
235
+
236
+ if (!audio) {
237
+ audio = adaptive_formats.find(i => checkBestAudio(i));
238
+ }
239
+
240
+ let fileMetadata = {
241
+ title: cleanString(basicInfo.title.trim()),
242
+ artist: cleanString(basicInfo.author.replace("- Topic", "").trim()),
243
+ }
244
+
245
+ if (basicInfo?.short_description?.startsWith("Provided to YouTube by")) {
246
+ let descItems = basicInfo.short_description.split("\n\n", 5);
247
+ if (descItems.length === 5) {
248
+ fileMetadata.album = descItems[2];
249
+ fileMetadata.copyright = descItems[3];
250
+ if (descItems[4].startsWith("Released on:")) {
251
+ fileMetadata.date = descItems[4].replace("Released on: ", '').trim();
252
+ }
253
+ }
254
+ }
255
+
256
+ let filenameAttributes = {
257
+ service: "youtube",
258
+ id: o.id,
259
+ title: fileMetadata.title,
260
+ author: fileMetadata.artist,
261
+ youtubeDubName: isDubbed ? o.dubLang : false
262
+ }
263
+
264
+ if (audio && o.isAudioOnly) return {
265
+ type: "audio",
266
+ isAudioOnly: true,
267
+ urls: audio.decipher(yt.session.player),
268
+ filenameAttributes: filenameAttributes,
269
+ fileMetadata: fileMetadata,
270
+ bestAudio: format === "h264" ? "m4a" : "opus"
271
+ }
272
+
273
+ const matchingQuality = Number(quality) > Number(bestQuality) ? bestQuality : quality,
274
+ checkSingle = i =>
275
+ qual(i) === matchingQuality && i.mime_type.includes(codecMatch[format].videoCodec),
276
+ checkRender = i =>
277
+ qual(i) === matchingQuality && i.has_video && !i.has_audio;
278
+
279
+ let match, type, urls;
280
+
281
+ // prefer good premuxed videos if available
282
+ if (!o.isAudioOnly && !o.isAudioMuted && format === "h264" && bestVideo.fps <= 30) {
283
+ match = info.streaming_data.formats.find(checkSingle);
284
+ type = "proxy";
285
+ urls = match?.decipher(yt.session.player);
286
+ }
287
+
288
+ const video = adaptive_formats.find(checkRender);
289
+
290
+ if (!match && video && audio) {
291
+ match = video;
292
+ type = "merge";
293
+ urls = [
294
+ video.decipher(yt.session.player),
295
+ audio.decipher(yt.session.player)
296
+ ]
297
+ }
298
+
299
+ if (match) {
300
+ filenameAttributes.qualityLabel = match.quality_label;
301
+ filenameAttributes.resolution = `${match.width}x${match.height}`;
302
+ filenameAttributes.extension = codecMatch[format].container;
303
+ filenameAttributes.youtubeFormat = format;
304
+ return {
305
+ type,
306
+ urls,
307
+ filenameAttributes,
308
+ fileMetadata
309
+ }
310
+ }
311
+
312
+ return { error: "fetch.fail" }
313
+ }
api/src/processing/url.js ADDED
@@ -0,0 +1,196 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import psl from "psl";
2
+ import { strict as assert } from "node:assert";
3
+
4
+ import { env } from "../config.js";
5
+ import { services } from "./service-config.js";
6
+ import { friendlyServiceName } from "./service-alias.js";
7
+
8
+ function aliasURL(url) {
9
+ assert(url instanceof URL);
10
+
11
+ const host = psl.parse(url.hostname);
12
+ const parts = url.pathname.split('/');
13
+
14
+ switch (host.sld) {
15
+ case "youtube":
16
+ if (url.pathname.startsWith('/live/') || url.pathname.startsWith('/shorts/')) {
17
+ url.pathname = '/watch';
18
+ // parts := ['', 'live' || 'shorts', id, ...rest]
19
+ url.search = `?v=${encodeURIComponent(parts[2])}`
20
+ }
21
+ break;
22
+
23
+ case "youtu":
24
+ if (url.hostname === 'youtu.be' && parts.length >= 2) {
25
+ /* youtu.be urls can be weird, e.g. https://youtu.be/<id>//asdasd// still works
26
+ ** but we only care about the 1st segment of the path */
27
+ url = new URL(`https://youtube.com/watch?v=${
28
+ encodeURIComponent(parts[1])
29
+ }`)
30
+ }
31
+ break;
32
+
33
+ case "pin":
34
+ if (url.hostname === 'pin.it' && parts.length === 2) {
35
+ url = new URL(`https://pinterest.com/url_shortener/${
36
+ encodeURIComponent(parts[1])
37
+ }`)
38
+ }
39
+ break;
40
+
41
+ case "vxtwitter":
42
+ case "fixvx":
43
+ case "x":
44
+ if (services.twitter.altDomains.includes(url.hostname)) {
45
+ url.hostname = 'twitter.com'
46
+ }
47
+ break;
48
+
49
+ case "twitch":
50
+ if (url.hostname === 'clips.twitch.tv' && parts.length >= 2) {
51
+ url = new URL(`https://twitch.tv/_/clip/${parts[1]}`);
52
+ }
53
+ break;
54
+
55
+ case "bilibili":
56
+ if (host.tld === 'tv') {
57
+ url = new URL(`https://bilibili.com/_tv${url.pathname}`);
58
+ }
59
+ break;
60
+
61
+ case "b23":
62
+ if (url.hostname === 'b23.tv' && parts.length === 2) {
63
+ url = new URL(`https://bilibili.com/_shortLink/${parts[1]}`)
64
+ }
65
+ break;
66
+
67
+ case "dai":
68
+ if (url.hostname === 'dai.ly' && parts.length === 2) {
69
+ url = new URL(`https://dailymotion.com/video/${parts[1]}`)
70
+ }
71
+ break;
72
+
73
+ case "facebook":
74
+ case "fb":
75
+ if (url.searchParams.get('v')) {
76
+ url = new URL(`https://web.facebook.com/user/videos/${url.searchParams.get('v')}`)
77
+ }
78
+ if (url.hostname === 'fb.watch') {
79
+ url = new URL(`https://web.facebook.com/_shortLink/${parts[1]}`)
80
+ }
81
+ break;
82
+
83
+ case "ddinstagram":
84
+ if (services.instagram.altDomains.includes(host.domain) && [null, 'd', 'g'].includes(host.subdomain)) {
85
+ url.hostname = 'instagram.com';
86
+ }
87
+ break;
88
+ }
89
+
90
+ return url
91
+ }
92
+
93
+ function cleanURL(url) {
94
+ assert(url instanceof URL);
95
+ const host = psl.parse(url.hostname).sld;
96
+
97
+ let stripQuery = true;
98
+
99
+ const limitQuery = (param) => {
100
+ url.search = `?${param}=` + encodeURIComponent(url.searchParams.get(param));
101
+ stripQuery = false;
102
+ }
103
+
104
+ switch (host) {
105
+ case "pinterest":
106
+ url.hostname = 'pinterest.com';
107
+ break;
108
+ case "vk":
109
+ if (url.pathname.includes('/clip') && url.searchParams.get('z')) {
110
+ limitQuery('z')
111
+ }
112
+ break;
113
+ case "youtube":
114
+ if (url.searchParams.get('v')) {
115
+ limitQuery('v')
116
+ }
117
+ break;
118
+ case "rutube":
119
+ if (url.searchParams.get('p')) {
120
+ limitQuery('p')
121
+ }
122
+ break;
123
+ }
124
+
125
+ if (stripQuery) {
126
+ url.search = ''
127
+ }
128
+
129
+ url.username = url.password = url.port = url.hash = ''
130
+
131
+ if (url.pathname.endsWith('/'))
132
+ url.pathname = url.pathname.slice(0, -1);
133
+
134
+ return url
135
+ }
136
+
137
+ function getHostIfValid(url) {
138
+ const host = psl.parse(url.hostname);
139
+ if (host.error) return;
140
+
141
+ const service = services[host.sld];
142
+ if (!service) return;
143
+ if ((service.tld ?? 'com') !== host.tld) return;
144
+
145
+ const anySubdomainAllowed = service.subdomains === '*';
146
+ const validSubdomain = [null, 'www', ...(service.subdomains ?? [])].includes(host.subdomain);
147
+ if (!validSubdomain && !anySubdomainAllowed) return;
148
+
149
+ return host.sld;
150
+ }
151
+
152
+ export function normalizeURL(url) {
153
+ return cleanURL(
154
+ aliasURL(
155
+ new URL(url.replace(/^https\/\//, 'https://'))
156
+ )
157
+ );
158
+ }
159
+
160
+ export function extract(url) {
161
+ if (!(url instanceof URL)) {
162
+ url = new URL(url);
163
+ }
164
+
165
+ const host = getHostIfValid(url);
166
+
167
+ if (!host) {
168
+ return { error: "link.invalid" };
169
+ }
170
+
171
+ if (!env.enabledServices.has(host)) {
172
+ return { error: "service.disabled" };
173
+ }
174
+
175
+ let patternMatch;
176
+ for (const pattern of services[host].patterns) {
177
+ patternMatch = pattern.match(
178
+ url.pathname.substring(1) + url.search
179
+ );
180
+
181
+ if (patternMatch) {
182
+ break;
183
+ }
184
+ }
185
+
186
+ if (!patternMatch) {
187
+ return {
188
+ error: "link.unsupported",
189
+ context: {
190
+ service: friendlyServiceName(host),
191
+ }
192
+ };
193
+ }
194
+
195
+ return { host, patternMatch };
196
+ }