├── .gitignore
├── LICENSE
├── README.md
├── jellyfin_id_scanner.py
└── jellyfin_migrator.py
/.gitignore:
--------------------------------------------------------------------------------
1 |
2 | *.pyc
3 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU AFFERO GENERAL PUBLIC LICENSE
2 | Version 3, 19 November 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU 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 |
633 | Copyright (C)
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
637 | by 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 .
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 | .
662 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Jellyfin-Migrator
2 |
3 | Script to migrate an entire Jellyfin database.
4 |
5 | **Update 2022-10-21: Confirmed! I successfully migrated my entire Jellyfin 10.8 installation from Windows to Docker on Linux.**
6 |
7 | ## Index
8 |
9 | * [Description](#description)
10 | * [Features](#features)
11 | * [Usage](#usage)
12 | * [Installation](#installation)
13 | * [Preparation / Recommended Steps](#preparation--recommended-steps)
14 | * [Configuration](#configuration)
15 | * [Test it](#test-it)
16 | * [Troubleshooting](#troubleshooting)
17 | * [Examples](#examples)
18 | * [ID Scanner](#id-scanner)
19 | * [Usage](#usage)
20 | * [Technical Documentation](#technical-documentation)
21 | * [Credits](#credits)
22 | * [License](#license)
23 |
24 | ## Description
25 |
26 | I wanted to migrate my Jellyfin installation from Windows to Docker on Linux. Turns out the Jellyfin database is a nightmare - to the point that it's simply not possible to migrate the installation without a script like this (details [below](#technical-documentation) for those that are interested).
27 |
28 | Sadly, such a script did not exist at that time so I created one. And it works! It's not a one-click solution for sure; you _will_ need to take some time configuring the script properly. However, I gave my best to give you all the resources you need within this readme. Please read it carefully. Installation, configuration, trouble shooting, detailed examples - it's all there.
29 |
30 | **Important**: This script is not maintained by the Jellyfin developers. If this script causes any issues, don't report them to the Jellyfin team. Check out the [Troubleshooting](#troubleshooting) instead if you're stuck.
31 |
32 | ## Features
33 |
34 | * Creates a complete copy of your Jellyfin database.
35 | * User settings and stats
36 | * Layout settings
37 | * Password
38 | * Titles watched, progress, ...
39 | * Metadata
40 | * All images, descriptions, etc.
41 | * Plugins
42 | * [Those that I have installed](#old-installation) migrated without issues. Might not be true in your case.
43 | * Fixes all paths
44 | * Allows for a pretty much arbitrary reorganization of the paths. This includes merging media files from different directories into the same one (need to be of the same type though. merging movies with music won't work).
45 | * Goes through all relevant files of the database and adjusts the paths.
46 | * Reorganizes the copied and adjusted files according to these paths.
47 | * Tested with Jellyfin 10.7.7 and 10.8. Unless the Jellyfin gets some major under-the-hood rework, I expect this script to remain compatible with future versions.
48 |
49 | Note: This script has been tested for migrations from Windows to Docker only. In theory it should be able to migrate from Docker to Windows, too. But a) I'm not sure anyone ever wanted to migrate in that direction and b) I'm not sure it actually works.
50 |
51 | ## Usage
52 |
53 | ### Installation
54 |
55 | While the script allows you to migrate to Linux (among many other possible migrations), I'm pretty sure the script itself must be executed on a Windows system. I haven't tested it but I think the script cannot work properly on Linux (if interested, details below in the [Technical Documentation](#why-is-the-script-windows-only)).
56 |
57 | * Install [Python](https://www.python.org/downloads/) 3.9 or higher (no guarantee for previous versions). On Windows, tick the option to add python to the PATH variable during the installation. No additional python modules required.
58 | * Download/Clone this repository, particularly the jellyfin_migrator.py file.
59 | * Install your new Jellyfin server. In particular, make sure the webinterface can be reached (a.k.a. the network configuration works) and complete the initial setup. It's not necessary to add any libraries, just make it to the homescreen.
60 |
61 | Optional:
62 |
63 | * [DB Browser for SQLite](https://sqlitebrowser.org/)
64 | * [Notepad++](https://notepad-plus-plus.org/)
65 | * [FileLocator Lite](https://www.mythicsoft.com/)
66 |
67 | ### Preparation / Recommended Steps
68 |
69 | * Copy your current Jellyfin database to a different folder. Since you're processing many small files, an SSD is highly recommended. You're not forced to copy your files before starting the migration, the script *can* work with the original files and won't modify them. However, I wouldn't recommend it and there are other reasons to not do it (see below).
70 | * Your target directory for the migration should be on an SSD, too. If you're on spinning drives though, I recommend putting source and target directory on separate drives (with an SSD both can be on the same drive without notable performance issue). Furthermore, your target directory does *not* need to be in your Docker container where Jellyfin will run later. You can migrate the database first and copy it to its actual destination afterwards.
71 | * Your Jellyfin database contains some files that don't need to be migrated and can (AFAIK!) safely be deleted. While this wouldn't hurt your current Jellyfin installation if you deleted the files in its database, I strongly recommend to only delete files in the copy (see above) - then you don't loose anything if I'm mistaken! Here are the paths for a typical Windows installation. You can probably figure out the matching paths for your installation, too.
72 | * `C:\ProgramData\Jellyfin\Server\cache`
73 | * `C:\ProgramData\Jellyfin\Server\log`
74 | * `C:\ProgramData\Jellyfin\Server\data\subtitles` - Note: these are actually only cached subtitles. Whenever Jellyfin's streaming a media file with embedded subtitles, it extracts them on the fly and saves them here. AFAIK no data is lost when deleting them. In any case, the script is *not* able to migrate these properly.
75 | * Plugins. The few [plugins from my installation](#old-installation) migrated without issues. You may have different ones though that require more attention. Plugins may come with their own `.db` database files. You need to open them and check every table and column for file paths and IDs that the script needs to process:
76 | * Open the database in the DB Browser (see [Installation](#installation)). Select the tab "Browse Data". Then you can select the table (think of it as a sheet within an Excel file) in the drop-down menu at the top left.
77 | * You need to check for all the columns if they contain paths. Some may have a lot of empty entries; in that case it's useful to sort them both ascending and descending. Then you're sure you don't have missed anything.
78 | * Some columns may contain more complex structures in which paths are embedded. In particular, this script supports embedded JSON strings and what I'd call "Jellyfin Image Metadata". If you search for "Jellyfin Image Metadata" within the script, you can find a comment that explains the format.
79 | * You also need to scan the database for IDs that may be used to identify the entries and their relations with other files. There's a script for that (see [ID Scanner](#id-scanner).
80 | * **Careful with your network configuration!** You might want to *not* migrate / overwrite that file, since networking in Docker is quite different than networking under Windows f.ex. I suggest you to keep the `network.xml` file from your new Jellyfin installation. Path to the file under Windows (once again, you can probably find the file in your case, too): `C:\ProgramData\Jellyfin\Server\config\network.xml`
81 |
82 | ### Configuration
83 |
84 | Every installation is different, therefore you need to adjust the paths in the script so that it matches your particular migration. This is the reason why you had get your new Jellyfin server already up and running; to make sure that you can figure out where all the files belong. Don't worry, you don't have to start from scratch. All the paths I had to adjust are still included in the script, so you'll know what to look for.
85 |
86 | This might seem complicated at first; I suggest you to check the [examples](#examples) below. They walk you through the process step by step!
87 |
88 | * Open the python file in your preferred text editor (if you have none, I recommend [Notepad++](#installation).
89 | * The entire file is fairly well commented. Though the interesting stuff for you as a user is all at the beginning of the file.
90 | * `log_file`: Please provide a filepath where the script can log everything it does. This is not optional.
91 | * `path_replacements`: Here you specify how the paths are adapted. Please read the notes in the python file.
92 | * The structure you see is what was required for my own migration from Windows to the Linuxserver.io Jellyfin Docker. It might be different in your case.
93 | * Please note that you need to specify the paths _as seen by Jellyfin_ when running within Docker (if you're using Docker).
94 | * Some of them are fairly straight-forward. Others, especially if you migrate to a different target than I did, require you to compare your old and new Jellyfin installation to figure out which files and folders end up where. Again, keep in mind that Docker may remap some of these which must be taken into account.
95 | * `fs_path_replacements`: "Undoing" the Docker mapping. This dictionary is used to figure out the actual location of the new files in the filesystem. In my case f.ex. `cache`, `log`, `data`, ... were mapped by Docker to `/config/cache`, `/config/log`, `/config/data` but those folders are actually placed in the root directory of this Docker container. This dictionary also lists the paths to all media files, because access to those is needed as well even if you don't copy them with this script.
96 | * `original_root`: original root directory of the Jellyfin database. On Windows this should be `C:\ProgramData\Jellyfin\Server`.
97 | * `source_root`: root directory of the database to migrate. This can (but doesn't need to) be different than `original_root`. Meaning, you can copy the entire `orignal_root` folder to some other place, specify that path here and run the script (f.ex. if you want to be 100% sure your original database doesn't get f*ed up. Unless you force the script it's read-only on the source but having a backup never hurts, right?).
98 | * `target_root`: target folder where the new database is created. This definitely should be another directory. It doesn't have to be the final directory though. F.ex. I specified some folder on my Windows system and copied that to my Linux server once it was done.
99 | * `todo_list_paths`, `todo_list_id_paths`, `todo_list_ids`: lists of files that need to be processed. This script supports `.db` (SQLite), `.xml`, `.json` and `.mblink` files. The given lists should work for "standard" Jellyfin instances. However, you might have some plugins that require additional files to be processed.
100 | * The list and their entries are documented in the Python file and / or should be self-explanatory.
101 |
102 | ### Test it
103 |
104 | * Run the script. Can easily take a few minutes.
105 | * To run the script (on Windows), open a CMD/PowerShell/... window in the folder with the python file (SHIFT + right click => open PowerShell here). Type `python jellyfin_migrator.py` and hit enter. Linux users probably know how to do it anyways.
106 | * Carefully check the log file for issues (See [Troubleshooting](#troubleshooting)).
107 | * As a first check after the script has finished, you can search through the new database for some of the old paths with any [search tool](#installation) that supports searching through file _contents_ (not only file names like the windows search). Assuming you omitted all the cache and log files there shouldn't be any hits. Well, except for the SQLite `.db` files. Apparently there's some sort of "lazy" updating which does not remove the old values entirely.
108 | * Copy the new database to your new server and run Jellyfin. Check the logs.
109 | * If there's any file system related error message there's likely something wrong. Either your `path_replacements` don't cover all paths, or some files ended up at places where they shouldn't be. I had multiple issues related to the Docker path mapping; took me a few tries to get the files where Docker expects them such that Jellyfin can actually see and access them.
110 |
111 | ## Troubleshooting
112 |
113 | This section lists the most common errors and what to do with them.
114 |
115 | If the tips and explanations below don't resolve your problem, check the [issues](https://github.com/MMMZZZZ/Jellyfin-Migrator/issues) of this project. Others might have had the same problem. If not, you can open a new issue.
116 | Another source of help can be the official Jellyfin chatrooms. With some luck, there's another user who's used this script successfully and can answer your question.
117 | If you're requesting help you should include your log file in some form.
118 |
119 | Click on the error messages below to show their description.
120 |
121 | General tips
122 |
123 | * Make sure your `todo_list`s (especially the `todo_list_paths`) actually cover all the files you want to copy / migrate. Jellyfins "core" files should already be covered correctly by the `todo_list`s as they are when downloading the script. However, you may have very different plugins or use very different features of Jellyfin than I do. The only indication that you got for missing files is a warning when updating the file dates (see [below](#file-doesnt-seem-to-exist-cant-update-its-dates-in-the-database)). This may not cover files from plugins though.
124 | * Inspect the log file with a decent text editor that allows you to quickly remove uninteresting messages. Here is my workflow for Notepad++ (see [Installation](#installation)):
125 | * Open log file in Notepad++
126 | * Text encoding is UTF-8 (selectable under "Encoding -> UTF-8")
127 | * Go to "Search -> Mark..." (CTRL + M)
128 | * Tick "Bookmark Line"
129 | * Search for strings that (only!) occur in the lines you want to remove. All those lines should get a marking next to the line number.
130 | * Go to "Search -> Bookmark -> Remove Bookmarked Lines"
131 | * Repeat as needed
132 |
133 |
134 |
135 | Warning! Working on original file! Continue?
136 |
137 | Apparently your paths are configured such that one or more file(s) would end up in the same place (meaning, their new path equals their old path).
138 |
139 | Causes and solutions:
140 |
141 | * Pretty sure your `source_root` and `target_root` paths are the same. If this is intentional, you can select to get no warnings anymore (until you restart the script)
142 | * Maybe some other paths you specified are wrong, too? Copy paste errors?
143 | * Check the previous log message(s) to see which path / job caused the issue.
144 |
145 |
146 |
147 | No entry for this (presumed) path
148 |
149 | While updating file paths or IDs within filepaths, the script encountered a string that might be a path but that it cannot process because it doesn't match any of the given replacement rules.
150 |
151 | Causes and solutions:
152 |
153 | * It's likely a false-positive and the string you see doesn't contain a path at all. The detection does skip the most common false-positives, but making it any better without risking to ignore actual paths wasn't worth the trouble IMO (since you can just ignore the false warnings).
154 | * The path points to a file you actually want to migrate (meaning, not a cache file or similar): Update your path replacement rules to include this and similar files.
155 | * It could be triggered by `fs_path_replacements` in cases where no `fs_path_replacements` are needed. See [Example 2](#example-2)
156 | * The path points to a file you don't want or need to migrate:
157 | * It happens while processing a .db file (scroll back up to find the log message that indicates what file it's processing): Update your rules anyways. Better safe than sorry when it comes to the database files IMO.
158 | * If it happens during the ID path migration (Step 3), it likely means that those paths use an ID type that the script doesn't support (yet). You can open an issue but I can't promise a fix.
159 |
160 |
161 |
162 | Warning! duplicates detected within new ids
163 |
164 | When generating the new IDs for the migrated database, the script found that some IDs occured more than once.
165 |
166 | Causes and solutions:
167 |
168 | * Most likely: Folders that used to be different are merged into the same new folder by your path replacement rules. This can be intentional if f.ex. you had media files spread across different drives and now move/copy them into the same folder. If that's indeed the case, you can ignore this message.
169 |
170 |
171 |
172 | Encountered duplicated entries | Deleting ...
173 |
174 | See [above](#warning-duplicates-detected-within-new-ids). This just informs you about the exact entries that have been deleted from the database.
175 |
176 |
177 |
178 | File doesn't seem to exist; can't update its dates in the database
179 |
180 | The script goes through all the migrated files and folders listed in the library database and tries to retrieve their creation and modified date from the file system. This message means that a file or folder listed in the database could not be found and thus its date can't be updated.
181 |
182 | Causes and solutions:
183 |
184 | * In my case this happened for a lot of metadata folders that were actually empty to begin with. I don't know why there were empty folders but okay. Since the script only copies *files*, those folders had not been copied. If you checked that in your original installation those directories were actually empty, it's probably (!) okay.
185 | * If you checked the original installation and there *are* files that should have been copied, your `todo_list_paths` likely doesn't cover all the files. Meaning, paths in the database have been updated, but the corresponding files haven't been copied.
186 | * If you know the files / folders exist, there's likely an issue with your `fs_path_replacements` dict. Make sure it properly maps the path shown in this message to the path required for this script to find the file (network drive mapping, Docker mappings, ...). Read the information here and in the script source about that dictionary for details.
187 |
188 |
189 |
190 | Server not accessible after migration
191 |
192 | Check out [Preparation / Recommended Steps](#preparation--recommended-steps). You likely overwrote Jellyfins network configuration file (`network.xml`), which is about the only file you don't necessarily want to migrate since your new installation likely has a different network setup than your previous one. Again, check out the details above.
193 |
194 | I also had the issue that the server just seemed to be unreachable (got the "Select Server" page or an error message on log in). In reality, it was just some browser cache issue. To verify that, try accessing your server from a private browser tab or even a different device. If you've verified that it's the browser cache, check how to delete it (restart probably helps). In my case (Firefox) CTRL+F5 did the job.
195 |
196 |
197 |
198 | ## Examples
199 |
200 | This section provides example configurations for two setups that were migrated with this script. By seeing the setups and the resulting configuration of this script I hope it gets more clear how to adapt it to your own setup.
201 |
202 | ### Example 1
203 |
204 | This was my own setup and corresponds to what you'll see in the scrip as well.
205 |
206 | #### Old Installation
207 |
208 | * Pretty standard Windows Installation
209 | * Metadata *not* located in the media folders, no NFO files there either.
210 | * Most of the stuff lives in C:/ProgramData/Jellyfin/Server/... Notably there are the following folders:
211 | * `cache`
212 | * `config`
213 | * `data`
214 | * `log`
215 | * `metadata`
216 | * `plugins`
217 | * `root`
218 | * `transcodes`
219 | * Media Folders:
220 | * `F:/Musik` (Music)
221 | * `F:/Filme` (Movies)
222 | * `F:/Serien` (TV Shows)
223 | * `D:/Serien` (more TV Shows)
224 | * Plugins:
225 | * AudioDB
226 | * Intros
227 | * MusicBrainz
228 | * OMDb
229 | * Open Subtitles
230 | * Playback Reporting
231 | * Studio Images
232 | * TMDb
233 | * TVmaze
234 | * TheTVDB
235 | * Theme Songs
236 | * YoutubeMetada
237 |
238 | #### New Installation
239 |
240 | * I went with the linuxserver.io Jellyifn Docker container that I deployed on an unraid server.
241 | * All the configuration stuff from Docker containers is stored at `/mnt/user/appdata/[container name]`, in particular, the path for the Jellyfin container is `mnt/user/appdata/jellyfin`.
242 | * The media files have already been copied and are located at
243 | * `/mnt/user/Media/Musik` (Music)
244 | * `/mnt/user/Media/Filme` (Movies)
245 | * `/mnt/user/Media/Serien` (all TV Shows, from both sources)
246 | * The default Docker mappings plus the media mappings look like this:
247 | * `/mnt/user/appdata/jellyfin`: `/config`
248 | * `/mnt/user/Media/Musik`: `/data/music`
249 | * `/mnt/user/Media/Filme`: `/data/movies`
250 | * `/mnt/user/Media/Serien`: `/data/tvshows`
251 |
252 | #### Script Location
253 |
254 | * The script, in my case, runs on a computer different from both the old and the new server. Though nothing would change if it ran on the old Windows server.
255 | * I copied my entire Jellyfin database from `C:/ProgramData/Jellyfin/Server/` to `D:/Jellyfin/Server/`
256 | * The migrated database shall end up in `D:/Jellyfin-patched`. From there I'll copy it to the new server.
257 |
258 | #### Determining the *_root Paths
259 |
260 | Easiest things first. In the old installation, the whole configuration was located at `C:/ProgramData/Jellyfin/Server`. So that's what you put in for `original_root`
261 |
262 | The script can find the files to migrate at `D:/Jellyfin/Server`. Thus, this is the value for `source_root`.
263 |
264 | Finally, the script shall put the resulting files at `D:/Jellyfin-patched`. Put this in `target_root`.
265 |
266 | #### Determining the Media Path Mappings
267 |
268 | Let's start with the media paths since they're easier IMO.
269 |
270 | From the perspective of Jellyfin, any movie that used to be found at `F:/Filme/somedir/somemovie.mkv` is now visible at `/data/movies/somedir/somemovie.mkv` (remember, Jellyfin sees the files and folders where they've been mapped by Docker). So we add the following entry to `path_replacements`:
271 | ```
272 | "F:/Filme": "/data/movies",
273 | ```
274 | Repeat for the other media locations and we get:
275 | ```
276 | "F:/Filme": "/data/movies",
277 | "F:/Musik": "/data/music",
278 | "F:/Serien": "/data/tvshows",
279 | "D:/Serien": "/data/tvshows",
280 | ```
281 | Note that you can indeed map both TV Show source folders to the same target folder. Nothing else is needed to merge them together.
282 |
283 | Those were the mappings for jellyfin. Now we need to determine how the script is going to access these files _on the new server_. Since my script doesn't run on that server, I created a network share for the `/mnt/user/Media` folder. On the computer that runs the script, this share is mounted under `Y:`. And thus `/mnt/user/Media/Filme` f.ex. ends up at `Y:/Filme`.
284 |
285 | So, to give the script access to the media files, I put this at the end of `fs_path_replacements`:
286 | ```
287 | "/data/tvshows": "Y:/Serien",
288 | "/data/movies": "Y:/Filme",
289 | "/data/music": "Y:/Musik",
290 | ```
291 |
292 | That's it. The script can now properly migrate the old paths to the new paths for Jellyfin, and based on the latter ones figure out where it can find the files itself.
293 |
294 | #### Determining the Config Path Mappings
295 |
296 | The config mappings can be more tricky to figure out depending on your Docker mappings. Once again, we first determine the mappings from Jellyfins perspective and then where the script is supposed to put the files on the disk.
297 |
298 | Let's take the example of the `C:/ProgramData/Jellyfin/Server/cache` directory. Looking at the root directory of our new Jellyfin installation (`/mnt/user/appdata/jellyfin`) we see a `cache` folder, too. And if we look at its content, we see that they're indeed both the same folders. Since Docker maps anything from `mnt/user/appdata/jellyfin` to `/config`, the `cache` subdirectory ends up being `/config/cache` for Jellyfin. This repeats for the `config` and `log` folders.
299 |
300 | Where things get interesting are the `metadata`, `plugin` and the other remaining folders from `C:/ProgramData/Jellyfin/Server`: Looking at the new installation, we find them at `mnt/user/appdata/jellyfin/data` - which is once again mapped by Docker to `/config/data`.
301 |
302 | There are multiple ways to construct the `path_replacements` dictionary from this. You can list all folders individually, but I took a slightly shorter approach:
303 |
304 | ```
305 | "C:/ProgramData/Jellyfin/Server/config": "/config/config",
306 | "C:/ProgramData/Jellyfin/Server/cache": "/config/
307 | "C:/ProgramData/Jellyfin/Server/log": "/config/
308 | "C:/ProgramData/Jellyfin/Server": "/config/data",
309 | ```
310 |
311 | The first three should be straightforward. The last one uses the fact that the replacements are processed in the exact order you list them. So after the first three entries, there are only folders left that need to go to `/config/data`. Therefore they don't need to be listed individually like the first three. However, you could just write
312 | ```
313 | "C:/ProgramData/Jellyfin/Server/metadata": "/config/data/metadata",
314 | ```
315 | (and repeat for all the remaining folders).
316 |
317 | As for `fs_path_replacements`, things are a bit different than in the case of the media folders. Anything Jellyfin sees under `/config` is actually located at `/mnt/user/appdata/jellyfin`, which is the _root_ folder for the Jellyfin Docker container. The script puts anything that goes to that path to `target_root`. So f.ex. `/config/data/metadata` shall end up at `target_root /data/metadata`. If you don't specify a full (absolute) path like for the media folders, but only `/data/metadata` f.ex., the script will automatically resolve it within the `target_root` folder. So the `fs_path_replacements` entry could look like this:
318 | ```
319 | "/config/data/metadata": "/data/metadata",
320 | ```
321 | And you'd repeat that for all folders. However, you'll notice that all these entries share one common thing: the `/config` part is removed. So instead of having all of them listed individually (which is perfectly fine if you don't miss any), all these cases can be covered by this simple entry:
322 | ```
323 | "/config": "/",
324 | ```
325 |
326 | #### %AppDataPath%, %MetadataPath%
327 |
328 | These are path variables, meaning, jellyfin replaces them with their actual location. The script needs to do the same. On one hand, we need to make sure the script recognizes them as paths - but we don't need to change them. Hence the `path_replacements` dict needs these two entries:
329 | ```
330 | "%AppDataPath%": "%AppDataPath%",
331 | "%MetadataPath%": "%MetadataPath%",
332 | ```
333 |
334 | If that doesn't make any sense to you, just ignore those lines and leave them as they are. Hopefully the next part makes more sense though. Just like Jellyfin, the script has to replace those variables, too, to locate the actual files (metadata files f.ex.). In the Windows installation, `%AppDataPath%` and `%MetadataPath%` point to `C:/ProgramData/Jellyfin/Server/data` and `C:/ProgramData/Jellyfin/Server/metadata` respectively. Applying the exact same logic as above, we get the following results for `fs_path_replacements`:
335 | ```
336 | "%AppDataPath%": "/data/data",
337 | "%MetadataPath%": "/data/metadata",
338 | ```
339 |
340 | You might want to go through this for yourself. It's not complicated, but the nested subfolders with identical names do make it confusing a.f.
341 |
342 | #### Plugins
343 |
344 | I'll keep this one short. From all the plugins I had installed, only one had its own database: Playback Reporting. Running the [ID Scanner](#id-scanner) for that `.db` file revealed one column with IDs that need to be replaced:
345 | ```
346 | Table Column ID Type(s) found
347 | PlaybackActivity ItemId ancestor-str (pure)
348 | ```
349 | A manual inspection revealed no file paths at all. The `playback_reporting.db` thus only needs to be added to the `todo_list_ids`:
350 | ```
351 | "source": source_root / "data/playback_reporting.db",
352 | "target": "auto-existing", # If you used "auto" in todo_list_paths, leave this on "auto-existing". Otherwise specify same path.
353 | "replacements": {"oldids": "newids"}, # Will be auto-generated during the migration.
354 | "tables": {
355 | "PlaybackActivity": {
356 | "str": [],
357 | "str-dash": [],
358 | "ancestor-str": [
359 | "ItemId",
360 | ],
361 | "ancestor-str-dash": [],
362 | "bin": [],
363 | },
364 | },
365 | ```
366 |
367 | That's it! These were the settings that brought my installation from Windows to Linux without data loss.
368 |
369 | ### Example 2
370 |
371 | This second example is from another user of the script. I won't go into too much details since the process is the same as for the first example. The most important differences are that both Jellyfin and Docker were configured for slightly different paths than in example 1.
372 |
373 | First of all, Docker was configured to mount `/mnt/user/appdata/jellyfin/config` as `/config` (compare that to the Docker mapping from example 1!). Secondly, the `metadata`, `plugin`, ... folders were _not_ located within a `data` subfolder. Oh, and his media folders were slightly different, of course.
374 |
375 | That first difference means, that `fs_path_replacements` does _not_ need the `"/config": "/",` entry, which has an important consequence (see below). The second one just makes the paths less confusing I guess. This person also opted for listing all folders individually; his dict could be written shorted but it worked perfectly fine like this.
376 |
377 | ```
378 | path_replacements = {
379 | "target_path_slash": "/",
380 |
381 | "E:/Séries": "/data/medias/Series",
382 | "E:/Films": "/data/medias/Films",
383 | "E:/Animés": "/data/medias/Animes",
384 |
385 | "C:/ProgramData/Jellyfin/Server/config": "/config/config",
386 | "C:/ProgramData/Jellyfin/Server/cache": "/cache",
387 | "C:/ProgramData/Jellyfin/Server/log": "/config/log",
388 | "C:/ProgramData/Jellyfin/Server/data": "/config/data",
389 | "C:/ProgramData/Jellyfin/Server/metadata": "/config/metadata",
390 | "C:/ProgramData/Jellyfin/Server/plugins": "/config/plugins",
391 | "C:/ProgramData/Jellyfin/Server/root": "/config/root",
392 | "C:/ProgramData/Jellyfin/Server/transcodes": "/config/transcodes",
393 | "C:/Program Files/Jellyfin/Server/ffmpeg.exe": "/config/usr/lib/jellyfin-ffmpeg/ffmpeg",
394 |
395 | "%MetadataPath%": "%MetadataPath%",
396 | "%AppDataPath%": "%AppDataPath%",
397 | }
398 |
399 | fs_path_replacements = {
400 | "log_no_warnings": True,
401 | "target_path_slash": "/",
402 | "%AppDataPath%": "/config/data",
403 | "%MetadataPath%": "/config/metadata",
404 | "/data/medias/Series": "M:/Series",
405 | "/data/medias/Films": "M:/Films",
406 | "/data/medias/Animes": "M:/Animes",
407 | }
408 | ```
409 |
410 | As teased above, the lack of the `/config` entry in `fs_path_replacements` means that many paths don't get changed by `fs_path_replacements` at all. This triggers a [warning](#no-entry-for-this-presumed-path) which - in this case - is a false positive. Therefore, if you are absolutely sure your `fs_path_replacements` are correct, you can (and should) set `"log_no_warnings"` to `True`. Careful! This blocks all warnings, and you may not notice issues with your `fs_path_replacements`!
411 |
412 | ## ID Scanner
413 |
414 | While developing the migrator script I wrote another tool that's contained in this repository: `jellyfin_id_scanner.py`. It scans a database for occurences of the IDs Jellyfin uses internally to identify files and folders and establish relations between them. This is helpful if you got database files from plugins that I don't have. Note that it can only tell you about ID formats it actually knows.
415 |
416 | ### Usage
417 |
418 | Unlike the main migrator script, this smaller one actually presents a command line interface (might also want to check the [Test it](#test-it) section above):
419 |
420 | ```
421 | python jellyfin_id_scanner.py --library-db "C:\Some\Path\library.db" --scan-db "C:\Some\JF\Pluging\PluginDB.db
422 | ```
423 |
424 | Using `--help` gives a more detailed description if required.
425 |
426 | ## Technical Documentation
427 |
428 | This section is dedicated to people who want to know what the script _actually_ does (but don't necessarily want to work their way through my source code). It only gives an overview; the source code definitely contains the more extensive documentation.
429 |
430 | The migration is a multi step process that not only modifies but also reorganizes Jellyfins database structures. The various formats involved (SQLite, JSON, XML, custom formats, pure text) make it impossible to do this "manually" or with some simple-ish SQL queries.
431 |
432 | ### Path adjustments
433 |
434 | Jellyfin mostly uses hardcoded, absolute paths. There are the `%MetadataPath%` and `%AppDataPath%` (no, the upper-/lowercase `data` is not a typo...) path variables, but even those paths use the operating systems slashes (meaning, `\` on Windows and `/` else). Jellyfin might find the files without adjusting the slashes, but I prefer to be safe here and many of them are updated for other reasons anyway ([see below](#item-ids)).
435 | Long story short, *every* file path is updated.
436 |
437 | This is what my first version of the script did. Update all paths everywhere. This is also where publicly available documentation ended at the time of writing this script (may-october 2022). Any tutorial and tool available on the internet does this (and only this) step.
438 | It works; everything seems to be there after the migration, but (as others noted, too) it doesn't survive a library scan. During the scan, Jellyfin "correctly" detects that all the old files are gone, thus deletes all metadata and rescans everything.
439 |
440 | I'm not sure whether only one or both of the next two steps fix this issue; in any case it's certainly the cleanest solution to have both steps.
441 |
442 | ### Item IDs
443 |
444 | Internally, Jellyfin identifies files, folders, ... by a unique 32 byte ID. Sounds like a good idea but the implementation is... well judge for yourself.
445 |
446 | The ID is calculated as MD5 of the type of the object as well as its file path. So to maintain a proper database, the IDs must be recalculated and updated whereever they occur. Interesting to note here that the MD5 function encodes those strings in UTF-16-le first (because why not I guess...).
447 | On top of that, the ID format is not consistent. Depending on the column of the database, it's either in binary form, string form or string form with dashes. However, there were many IDs left that did not match the Item IDs described so far. Only by comparing what _should_ belong together did I notice that sometimes Jellyfin swaps the byte ordering within the IDs. Boy was I banging my head onto the desk when discovering this...
448 |
449 | These different IDs of course occur in the database files. More annoyingly (though this kinda makes sense tbh), they also occur in the metadata file paths (among others). Meaning, the script not only checks and updates all the files but also their locations if an ID is detected in their file paths. Luckily, file paths seem to only use a single type of the various ID flavors presented above. Though at this point it wouldn't really matter anymore.
450 |
451 | ### File Dates
452 |
453 | Jellyfin's main database (`library.db`) also stores file creation and modification dates. I assume (!) that these are used to check if a file has been altered on the file system and that a mismatch would trigger a rescan. Therefore I decided to update these, too. This is the reason why the script needs access to the media files _after being moved/copied to the new server_; to read the "final" file creation and modification dates.
454 |
455 | Note that this opens a whoooole new can of worms, namely time zones, leap years, ... (also see the next section). Luckily, it seems like the default settings for how to read/format date codes from files give the correct results. I really have a "it works. LEAVE IT." approach to this topic and pray that those default settings work for others, too. Again, see the next point for this.
456 |
457 | ### Subtitles (useless)
458 |
459 | While scanning my installation for IDs to see if there are even more flavors than those listed above I actually found some (ugh...)! The internally stored subtitle files (`.../data/subtitles`) use yet another form of ID that includes the file modification date as .NET ticks ([relevant Jellyfin source code](https://github.com/jellyfin/jellyfin/blob/ac0dbd0b40b51753cb0a431f2fbc1c4e5a843aaf/MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs#L672-L694)). So what are these ticks? Simple (or so I thought...). They're the number of 100ns intervals since some-long-time-ago-random-date (or epoch for short). That means that I need to recreate the .NET time math _down to the nanoseconds_ to properly calculate the hashes. The issue is that Python and .NET implement time functions and measurement differently. To make matter worse, they're both cross-platform ecosystems. Why is that an issue? Well, operating systems handle time very differently, too (resolution f.ex.). The reason this is so bad is that .NET and Python both use to varying degrees their own settings/presets and those from the system. This doesn't really matter if you want to now "what time and date do we have right now". However, if you're counting _nanoseconds since the epoch_ everyhting matters. Are leap years included (usually yes)? Leap days (no clue)? Leap seconds (usually no)? What if the system does not use the gregorian calendar? What resolution does the operating system provide me with? Can my language handle that resolution? Spoiler: nope. Python generally doesn't support date/time with higher than 1us resolution. DOES NOT HELP.
460 |
461 | Jellyfin's databases might be a mess but it seems almost clean in comparison to computer date/time formats.
462 |
463 | Only later did I realize that these were actually just cache files and don't need to be migrated so I quickly moved on. Pfiu.
464 |
465 | ### Encodings.......
466 |
467 | Encodings definitely compete with date/time formats on the messiness scale. AFAIK Jellyfin encodes its files all in UTF-8. While I think that my script handles them properly, I did encounter various issues with metadata and subtitle providers in my old installation when I used non-ASCII characters. So I'd still strongly advise you to not use any non-ASCII characters in your media folder and file names. Sad that this is still such an issue in 2022.
468 | (also, if you're reading this, it's likely way too late for such a recommendation).
469 |
470 | ### Why is the script Windows only?
471 |
472 | The short answer: because of this part of the code: https://github.com/MMMZZZZ/Jellyfin-Migrator/blob/85c095f0ab1db00b7ec7a85718fefec9538a6888/jellyfin_migrator.py#L831-L836
473 |
474 | On Windows, paths starting with a `/` are not considered as absolute paths which is very convenient for this script because it allows to distinguish f.ex. between "real" paths (`D:/target folder/some.file`) and "virtual" Docker paths (`/mapped/folder/some.file`). On Linux however, both real and virtual paths would start with `/` and this method doesn't work anymore. There is for sure a way to fix this but I cannot see an easy one.
475 |
476 | ## Credits
477 |
478 | Big thank you goes to the devs in the [official Jellyfin chats](https://jellyfin.org/contact) that pointed me to the correct places in the Jellyfin sources and helped me figure out how certain things work under the hood!
479 |
480 | Also, apologies for possible future bug reports from people using my tool and encountering weird issues with their Jellyfin installation. I sincerely hope it won't happen.
481 |
482 | ## License
483 |
484 | Jellyfin Migrator - Adjusts your Jellyfin database to run on a new system.
485 | Copyright (C) 2022 Max Zuidberg
486 |
487 | This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
488 |
489 | This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
490 |
491 | You should have received a copy of the GNU Affero General Public License along with this program. If not, see .
492 |
--------------------------------------------------------------------------------
/jellyfin_id_scanner.py:
--------------------------------------------------------------------------------
1 | # Jellyfin ID Scanner - Searches through database files for occurences of jellyfin IDs
2 | # Copyright (C) 2022 Max Zuidberg
3 | #
4 | # This program is free software: you can redistribute it and/or modify
5 | # it under the terms of the GNU Affero General Public License as published by
6 | # the Free Software Foundation, either version 3 of the License, or
7 | # (at your option) any later version.
8 | #
9 | # This program is distributed in the hope that it will be useful,
10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | # GNU Affero General Public License for more details.
13 | #
14 | # You should have received a copy of the GNU Affero General Public License
15 | # along with this program. If not, see .
16 |
17 |
18 | import sqlite3
19 | import binascii
20 | from multiprocessing import Pool
21 | import argparse
22 |
23 |
24 | ids = dict()
25 |
26 |
27 | # Functions used for converting IDs between the various formats. See load_ids
28 | # convert_ancestor_id: regroup bytes to convert from/to ancestor id format (symetric)
29 | def convert_ancestor_id(id: str):
30 | # Group by bytes
31 | id = [id[i : i+2] for i in range(0, len(id), 2)]
32 |
33 | # Reorder (not sure why it's done like this but it is)
34 | # and convert back to string.
35 | # Note that only the first 8 bytes are rearranged, the others remain.
36 | byte_order = (3, 2, 1, 0, 5, 4, 7, 6)
37 | swapped_id = [id[i] for i in byte_order]
38 | swapped_id.extend(id[8:])
39 | return "".join(swapped_id)
40 | # bid2sid: binary id to string id
41 | def bid2sid(id): return binascii.b2a_hex(id).decode("ascii")
42 | # sid2bid: string id to binary id
43 | def sid2bid(id): return binascii.a2b_hex(id)
44 | # sid2did: string id to dashed string id
45 | def sid2did(id): return "-".join([id[:8], id[8:12], id[12:16], id[16:20], id[20:]])
46 |
47 |
48 | # Loads all IDs from jellyfins library.db file.
49 | # Additionally, it generates all the variants of each ID that may be used.
50 | # GUIDs of the following formats have been found / are assumed to exist:
51 | # * binary: b'\x83:\xdd\xde\x99(\x93\xe9=\x05r\x90\x7f\x8bL\xad'
52 | # * string: '833addde992893e93d0572907f8b4cad'
53 | # * string with dashes: '833addde-9928-93e9-3d05-72907f8b4cad'
54 | # * All of these formats exist in another variant, called "ancestor" (because they're
55 | # primarily used to identify ancestors of objects). The ancestor versions have the
56 | # bytes rearranged in a different order for God knows what reason (see convert_ancestor_id)
57 | # * ancestor binary: b'\xde\xdd:\x83(\x99\xe9\x93=\x05r\x90\x7f\x8bL\xad'
58 | # * ancestor string: 'dedd3a832899e9933d0572907f8b4cad'
59 | # * ancestor string with dashes: 'dedd3a83-2899-e993-3d05-72907f8b4cad'
60 | # * in paths they're grouped in folders by the first two letters:
61 | # '.../83/833addde992893e93d0572907f8b4cad/...'
62 | def load_ids(library_db:str):
63 | con = sqlite3.connect(library_db)
64 | cur = con.cursor()
65 | id_replacements_bin = [x[0] for x in cur.execute("SELECT `guid` FROM `TypedBaseItems`")]
66 | con.close()
67 |
68 | id_str = [bid2sid(k) for k in id_replacements_bin]
69 | id_str_dash = [sid2did(k) for k in id_str]
70 | id_ancestor_str = [convert_ancestor_id(k) for k in id_str]
71 | id_ancestor_bin = [sid2bid(k) for k in id_ancestor_str]
72 | id_ancestor_str_dash = [sid2did(k) for k in id_ancestor_str]
73 |
74 | ids = {
75 | "bin": id_replacements_bin,
76 | "str": id_str,
77 | "str-dash": id_str_dash,
78 | "ancestor-bin": id_ancestor_bin,
79 | "ancestor-str": id_ancestor_str,
80 | "ancestor-str-dash": id_ancestor_str_dash,
81 | }
82 |
83 | print(f"{len(id_replacements_bin)} IDs loaded from library.db")
84 |
85 | byteids = dict()
86 | for k, v in ids.items():
87 | if "bin" in k:
88 | byteids[k] = v
89 | else:
90 | byteids[k] = [s.encode("ascii") for s in v]
91 | ids = {k: v for k, v in ids.items() if "bin" not in k}
92 | return ids, byteids
93 |
94 |
95 | # Loads the name of all tables in a sqlite db file as well as each one's columns.
96 | def load_db_tables_columns(path_to_db):
97 | con = sqlite3.connect(path_to_db)
98 | cur = con.cursor()
99 |
100 | # Get all table names. The query will also return index stuff that isn't required. It's (mostly) filtered.
101 | table_names = [
102 | x[0] for x in cur.execute("SELECT name from sqlite_master")
103 | if not x[0].startswith("idx")
104 | and not x[0].startswith("sqlite_autoindex")
105 | and x[0][-6:-1].lower() != "index"
106 | ]
107 |
108 | # For each table, get all column names.
109 | table_info = {n: [x[0] for x in cur.execute(f"SELECT name FROM PRAGMA_TABLE_INFO('{n}')")] for n in table_names}
110 |
111 | con.close()
112 |
113 | return table_info
114 |
115 |
116 | # Returns a list with all rows of all tables, no column excluded.
117 | def load_all_rows(path_to_db):
118 | table_info = load_db_tables_columns(path_to_db)
119 |
120 | con = sqlite3.connect(path_to_db)
121 | cur = con.cursor()
122 |
123 | rows = []
124 |
125 | for table, columns in table_info.items():
126 | for column in columns:
127 | col_values = {x[0] for x in cur.execute(f"SELECT `{column}` FROM `{table}`") if x[0]}
128 | if not col_values:
129 | continue
130 | rows.append([table, column, col_values])
131 |
132 | con.close()
133 |
134 | return rows
135 |
136 |
137 | # Scans a job (entire column) for occurrences of any ID in binary (BLOB) format.
138 | # Binary IDs are always "pure", meaning not embedded within a string with other stuff.
139 | def check_bin_ids(job):
140 | table, column, column_values, byteids = job
141 | id_types = set()
142 |
143 | if not type(next(iter(column_values))) is bytes:
144 | return
145 |
146 | for id_type, values in byteids.items():
147 | for value in values:
148 | if value in column_values:
149 | id_types.add(id_type + " (pure)")
150 | if id_types:
151 | result = table, column, id_types
152 | return result
153 |
154 |
155 | # Scans a job (entire column) for occurrences of any ID in any string format.
156 | # Column entries can either be pure (just the ID string) or have an ID string
157 | # embedded into other stuff (JSON string f.ex.).
158 | # The function also checks if more than one ID format is found within the column.
159 | def check_embedded_id_types(job):
160 | table, column, column_values, ids = job
161 | id_types = set()
162 | check_for_next_type = False
163 |
164 | for id_type, values in ids.items():
165 | for value in values:
166 | for column_type, column_value in column_values:
167 | if value in column_value:
168 | id_types.add(f"{id_type} ({column_type})")
169 | check_for_next_type = True
170 | if check_for_next_type:
171 | break
172 | if check_for_next_type:
173 | break
174 | if id_types:
175 | result = table, column, id_types
176 | return result
177 |
178 |
179 | # Takes an arbitrary string or byte-string and returns a set with all the chunks
180 | # from it that could be an ID: sequences of >=32 hexadecimal digits
181 | # (plus the - symbol used in some ID formats).
182 | def get_id_candidates(s):
183 | result = ""
184 | if type(s) is bytes:
185 | result = "".join(chr(c) if c in b"0123456789abcdef-" else " " for c in s)
186 | elif type(s) is str:
187 | result = "".join(c if c in "0123456789abcdef-" else " " for c in s)
188 |
189 | # check if it's a pure id or an id embedded within other data.
190 | column_type = "embedded"
191 | if result == s:
192 | column_type = "pure"
193 |
194 | result = result.split(" ")
195 | result = {piece for piece in result if len(piece) >= 32}
196 | return column_type, result
197 |
198 |
199 | if __name__ == "__main__":
200 | desc = """
201 | Jellyfin ID Scanner - Searches through database files for occurences of jellyfin IDs
202 | Copyright (C) 2022 Max Zuidberg
203 | This program is free software: you can redistribute it and/or modify
204 | it under the terms of the GNU Affero General Public License as published by
205 | the Free Software Foundation, either version 3 of the License, or
206 | (at your option) any later version.
207 | """
208 | parser = argparse.ArgumentParser(description=desc)
209 | parser.add_argument("--library-db", type=str, required=True,
210 | help="Path to Jellyfins library.db file. Always required")
211 | parser.add_argument("--scan-db", type=str, required=True,
212 | help="Path to the db file to scan. Can also be library.db or f.ex. a db file from a plugin. "
213 | "Other file types are currently unsupported but should be easy to add. Always required")
214 |
215 | args = parser.parse_args()
216 |
217 | print("Loading IDs from library.db")
218 | ids, byteids = load_ids(args.library_db)
219 |
220 | print("Loading db to scan")
221 | jobs = [row + [byteids] for row in load_all_rows(args.scan_db)]
222 | values = sum([len(job[2]) for job in jobs])
223 | print(f"Loaded {values} values.")
224 |
225 | print("Scanning... This will take a while. Example: scanning a library.db file with 78k IDs "
226 | "and 1.2M entries took about 5 minutes.")
227 | results = []
228 | with Pool() as p:
229 | results.extend(p.map(check_bin_ids, jobs, chunksize=64))
230 |
231 | # Search through all values for ID occurences. to speed this up,
232 | # remove anything that for sure doesn't match, like shorter items or non alphanum chars.
233 | for i, job in enumerate(jobs):
234 | col_values = job[2]
235 | with Pool() as p:
236 | col_values = [x for x in p.imap_unordered(get_id_candidates, col_values, chunksize=64) if x[1]]
237 | jobs[i] = (job[0], job[1], col_values, ids)
238 |
239 | check_embedded_id_types(jobs[i])
240 | with Pool() as p:
241 | results.extend(p.map(check_embedded_id_types, jobs, chunksize=1))
242 |
243 | # Remove empty results, sort them for convenience, and format them for pretty printing.
244 | results = [[x[0], x[1], ", ".join(x[2])] for x in results if x]
245 | results.sort(key=lambda x:"".join(x))
246 | results = [["Table", "Column", "ID Type(s) found"]] + results
247 | lengths = [max([len(x) for x in col]) for col in zip(*results)]
248 | results = [[x[i].ljust(lengths[i] + 1) for i in range(len(x))] for x in results]
249 | for x in results:
250 | print(*x)
251 |
--------------------------------------------------------------------------------
/jellyfin_migrator.py:
--------------------------------------------------------------------------------
1 | # Jellyfin Migrator - Adjusts your Jellyfin database to run on a new system.
2 | # Copyright (C) 2022 Max Zuidberg
3 | #
4 | # This program is free software: you can redistribute it and/or modify
5 | # it under the terms of the GNU Affero General Public License as published by
6 | # the Free Software Foundation, either version 3 of the License, or
7 | # (at your option) any later version.
8 | #
9 | # This program is distributed in the hope that it will be useful,
10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | # GNU Affero General Public License for more details.
13 | #
14 | # You should have received a copy of the GNU Affero General Public License
15 | # along with this program. If not, see .
16 |
17 |
18 | import pathlib
19 | import sqlite3
20 | import json
21 | import hashlib
22 | import binascii
23 | import xml.etree.ElementTree as ET
24 | from pathlib import Path
25 | from shutil import copy
26 | from time import time
27 | from jellyfin_id_scanner import *
28 | import datetime
29 | from string import ascii_letters
30 | import os
31 |
32 |
33 | # TODO BEFORE YOU START:
34 | # * Create a copy of the jellyfin database you want to migrate
35 | # * Delete the following temp/cache folders (resp. the matching
36 | # folders for your installation)
37 | # * C:/ProgramData/Jellyfin/Server/cache
38 | # * C:/ProgramData/Jellyfin/Server/log
39 | # * C:/ProgramData/Jellyfin/Server/data/subtitles
40 | # Note: this only contains *cached* subtitles that have been
41 | # extracted on-the-fly from files streamed to clients.
42 | # * RTFM (read the README.md) and you're ready to go.
43 | # * Careful when replacing everything in your new installation,
44 | # you might want to *not* copy your old network settings
45 | # (C:/ProgramData/Jellyfin/Server/config/networking.xml)
46 |
47 |
48 | # Please specify a log file. The script is rather verbose and important
49 | # errors might get lost in the process. You should definitely check the
50 | # log file after running the script to see if there are any warnings or
51 | # other important messages! Use f.ex. notepad++ (npp) to quickly
52 | # highlight and remove bunches of uninteresting log messages:
53 | # * Open log file in npp
54 | # * Go to "Search -> Mark... (CTRL + M)"
55 | # * Tick "Bookmark Line"
56 | # * Search for strings that (only!) occur in the lines you want to
57 | # remove. All those lines should get a marking next to the line number.
58 | # * Go to "Search -> Bookmark -> Remove Bookmarked Lines"
59 | # * Repeat as needed
60 | # Text encoding is UTF-8 (in npp selectable under "Encoding -> UTF-8")
61 | log_file = "D:/jf-migrator.log"
62 |
63 |
64 | # These paths will be processed in the order they're listed here.
65 | # This can be very important! F.ex. if specific subfolders go to a different
66 | # place than stuff in the root dir of a given path, the subfolders must be
67 | # processed first. Otherwise, they'll be moved to the same place as the other
68 | # stuff in the root folder.
69 | # Note: all the strings below will be converted to Path objects, so it doesn't
70 | # matter whether you write / or \\ or include a trailing / . After the path
71 | # replacement it will be converted back to a string with slashes as specified
72 | # by target_path_slash.
73 | # Note2: The AppDataPath and MetadataPath entries are only there to make sure
74 | # the script recognizes them as actual paths. This is necessary to adjust
75 | # the (back)slashes as specified. This can only be done on "known" paths
76 | # because (back)slashes occur in other strings, too, where they must not be
77 | # changed.
78 | path_replacements = {
79 | # Self-explanatory, I guess. "\\" if migrating *to* Windows, "/" else.
80 | "target_path_slash": "/",
81 | # Paths to your libraries
82 | "D:/Serien": "/data/tvshows",
83 | "F:/Serien": "/data/tvshows",
84 | "F:/Filme": "/data/movies",
85 | "F:/Musik": "/data/music",
86 | # Paths to the different parts of the jellyfin database. Determine these
87 | # by comparing your existing installation with the paths in your new
88 | # installation.
89 | "C:/ProgramData/Jellyfin/Server/config": "/config",
90 | "C:/ProgramData/Jellyfin/Server/cache": "/config/cache",
91 | "C:/ProgramData/Jellyfin/Server/log": "/config/log",
92 | "C:/ProgramData/Jellyfin/Server": "/config/data", # everything else: metadata, plugins, ...
93 | "C:/ProgramData/Jellyfin/Server/transcodes": "/config/data/transcodes",
94 | "C:/Program Files/Jellyfin/Server/ffmpeg.exe": "usr/lib/jellyfin-ffmpeg/ffmpeg",
95 | "%MetadataPath%": "%MetadataPath%",
96 | "%AppDataPath%": "%AppDataPath%",
97 | }
98 |
99 |
100 | # This additional replacement dict is required to convert from the paths docker
101 | # shows to jellyfin back to the actual file system paths to figure out where
102 | # the files shall be copied. If relative paths are provided, the replacements
103 | # are done relative to target_root.
104 | #
105 | # Even if you're not using docker or not using path mapping with docker,
106 | # you probably do need to add some entries for accessing the media files
107 | # and appdata/metadata files. This is because the script must read all the
108 | # file creation and modification dates *as seen by jellyfin*.
109 | # In that case and if you're sure that this list is 100% correct,
110 | # *and only then* you can set "log_no_warnings" to True. Otherwise your logs
111 | # will be flooded with warnings that it couldn't find an entry to modify the
112 | # paths (which in that case would be fine because no modifications are needed).
113 | #
114 | # If you actually don't need any of this (f.ex. running the script in the
115 | # same environment as jellyfin), remove all entries except for
116 | # * "log_no_warnings" (again, can be set to true if you're sure)
117 | # * "target_path_slash"
118 | # * %AppDataPath%
119 | # * %MetadataPath%.
120 | fs_path_replacements = {
121 | "log_no_warnings": False,
122 | "target_path_slash": "/",
123 | "/config": "/",
124 | "%AppDataPath%": "/data/data",
125 | "%MetadataPath%": "/data/metadata",
126 | "/data/tvshows": "Y:/Serien",
127 | "/data/movies": "Y:/Filme",
128 | "/data/music": "Y:/Musik",
129 | }
130 |
131 |
132 | # Original root only needs to be filled if you're using auto target paths _and_
133 | # if your source dir doesn't match the source paths specified above in
134 | # path_replacements.
135 | # auto target will first replace source_root with original_root in a given path
136 | # and then do the replacement according to the path_replacements dict.
137 | # This is required if you copied your jellyfin DB to another location and then
138 | # start processing it with this script.
139 | original_root = Path("C:/ProgramData/Jellyfin/Server")
140 | source_root = Path("D:/Jellyfin/Server")
141 | target_root = Path("D:/Jellyfin-dummy")
142 |
143 |
144 | ### The To-Do Lists: todo_list_paths, todo_list_id_paths and todo_list_ids.
145 | # If your installation is like mine, you don't need to change the following three todo_lists.
146 | # They contain which files should be modified and how.
147 | # The migration is a multistep process:
148 | # 1. Specified files are copied to the new location according to the path changes listed above
149 | # 2. All paths within those files are updated to match the new location
150 | # 3. The IDs that are used internally and are derived from the paths are updated
151 | # 1. They occur in jellyfins file paths, so these paths are updated both on the disk and in the databases.
152 | # 2. All remaining occurences of any IDs are updated throughout all files.
153 | # 4. Now that all files are where and how they should be, update the file creation and modification
154 | # dates in the database.
155 | # todo_list_paths is used for step 1 and 2
156 | # todo_list_id_paths is used for step 3.1
157 | # todo_list_ids is used for step 3.2
158 | # table and columns for step 4 are hardcoded / determined automatically.
159 | #
160 | # General Notes:
161 | # * For step 1, "path_replacements" is used to determine the new file paths.
162 | # * In step 2, the "replacements" from the todo_list is used, but it makes no sense to set it
163 | # to something different from what you used in step 1.
164 | # * In step 3 the "replacements" entry in the todo_lists is auto-generated, no need to touch it either.
165 | #
166 | # Notes from my own jellyfin installation:
167 | # 3.1 seems to be "ancestor-str" and "ancestor" formatted IDs only (see jellyfin_id_scanner for details on the format)
168 | # 3.2 seems like only certain .db files contain them.
169 | # Search for "ID types occurring in paths" to find the place in the code
170 | # where you can select the types to include.
171 | todo_list_paths = [
172 | {
173 | "source": source_root / "data/library.db",
174 | "target": "auto", # Usually you want to leave this on auto. If you want to work on the source file, set it to the same path (YOU SHOULDN'T!).
175 | "replacements": path_replacements, # Usually same for all but you could specify a specific one per db.
176 | "tables": {
177 | "TypedBaseItems": { # Name of the table within the SQLite database file
178 | "path_columns": [ # All column names that can contain paths.
179 | "path",
180 | ],
181 | "jf_image_columns": [ # All column names that can jellyfins "image paths mixed with image properties" strings.
182 | "Images",
183 | ],
184 | "json_columns": [ # All column names that can contain json data with paths.
185 | "data",
186 | ],
187 | },
188 | "mediastreams": {
189 | "path_columns": [
190 | "Path",
191 | ],
192 | },
193 | "Chapters2": {
194 | "jf_image_columns": [
195 | "ImagePath",
196 | ],
197 | },
198 | },
199 | },
200 | {
201 | "source": source_root / "data/jellyfin.db",
202 | "target": "auto",
203 | "replacements": path_replacements,
204 | "tables": {
205 | "ImageInfos": {
206 | "path_columns": [
207 | "Path",
208 | ],
209 | },
210 | },
211 | },
212 | # Copy all other .db files. Since it's copy-only (no path adjustments), omit the log output.
213 | {
214 | "source": source_root / "data/*.db",
215 | "target": "auto",
216 | "replacements": path_replacements,
217 | "copy_only": True,
218 | "no_log": True,
219 | },
220 |
221 | {
222 | "source": source_root / "plugins/**/*.json",
223 | "target": "auto",
224 | "replacements": path_replacements,
225 | },
226 |
227 | {
228 | "source": source_root / "config/*.xml",
229 | "target": "auto",
230 | "replacements": path_replacements,
231 | },
232 |
233 | {
234 | "source": source_root / "metadata/**/*.nfo",
235 | "target": "auto",
236 | "replacements": path_replacements,
237 | },
238 |
239 | {
240 | # .xml, .mblink, .collection files are here.
241 | "source": source_root / "root/**/*.*",
242 | "target": "auto",
243 | "replacements": path_replacements,
244 | },
245 |
246 | {
247 | "source": source_root / "data/collections/**/collection.xml",
248 | "target": "auto",
249 | "replacements": path_replacements,
250 | },
251 |
252 | {
253 | "source": source_root / "data/playlists/**/playlist.xml",
254 | "target": "auto",
255 | "replacements": path_replacements,
256 | },
257 |
258 | # Lastly, copy anything that's left. Any file that's already been processed/copied is skipped
259 | # ... you should delete the cache and the logs though.
260 | {
261 | "source": source_root / "**/*.*",
262 | "target": "auto",
263 | "replacements": path_replacements,
264 | "copy_only": True,
265 | "no_log": True,
266 | },
267 | ]
268 |
269 | # See comment from todo_list_paths for details about this todo_list.
270 | # "replacements" designates the source -> target path replacement dict.
271 | # Same as for the matching job in todo_list_paths.
272 | # The ID replacements are determined automatically.
273 | todo_list_id_paths = [
274 | {
275 | "source": source_root / "data/library.db",
276 | "target": "auto-existing", # If you used "auto" in todo_list_paths, leave this on "auto-existing". Otherwise specify same path.
277 | "replacements": {"oldids": "newids"}, # Will be auto-generated during the migration.
278 | "tables": {
279 | "TypedBaseItems": { # Name of the table within the SQLite database file
280 | "path_columns": [ # All column names that can contain paths.
281 | "path",
282 | ],
283 | "jf_image_columns": [ # All column names that can jellyfins "image paths mixed with image properties" strings.
284 | "Images",
285 | ],
286 | "json_columns": [ # All column names that can contain json data with paths OR IDs!!
287 | "data",
288 | ],
289 | },
290 | "mediastreams": {
291 | "path_columns": [
292 | "Path",
293 | ],
294 | },
295 | "Chapters2": {
296 | "jf_image_columns": [
297 | "ImagePath",
298 | ],
299 | },
300 | },
301 | },
302 |
303 | {
304 | "source": source_root / "config/*.xml",
305 | "target": "auto-existing", # If you used "auto" in todo_list_paths, leave this on "auto-existing". Otherwise specify same path.
306 | "replacements": {"oldids": "newids"}, # Will be auto-generated during the migration.
307 | },
308 |
309 | {
310 | "source": source_root / "metadata/**/*",
311 | "target": "auto-existing", # If you used "auto" in todo_list_paths, leave this on "auto-existing". Otherwise specify same path.
312 | "replacements": {"oldids": "newids"}, # Will be auto-generated during the migration.
313 | },
314 |
315 | {
316 | # .xml, .mblink, .collection files are here.
317 | "source": source_root / "root/**/*",
318 | "target": "auto-existing", # If you used "auto" in todo_list_paths, leave this on "auto-existing". Otherwise specify same path.
319 | "replacements": {"oldids": "newids"}, # Will be auto-generated during the migration.
320 | },
321 |
322 | {
323 | "source": source_root / "data/**/*",
324 | "target": "auto-existing", # If you used "auto" in todo_list_paths, leave this on "auto-existing". Otherwise specify same path.
325 | "replacements": {"oldids": "newids"}, # Will be auto-generated during the migration.
326 | },
327 | ]
328 |
329 | # See comment from todo_list_paths for details about this todo_list.
330 | # "replacements" designates the source -> target path replacement dict.
331 | # The ID replacements are determined automatically.
332 | todo_list_ids = [
333 | {
334 | "source": source_root / "data/library.db",
335 | "target": "auto-existing", # If you used "auto" in todo_list_paths, leave this on "auto-existing". Otherwise specify same path.
336 | "replacements": {"oldids": "newids"}, # Will be auto-generated during the migration.
337 | "tables": {
338 | "AncestorIds": {
339 | "str": [],
340 | "str-dash": [],
341 | "ancestor-str": [
342 | "AncestorIdText",
343 | ],
344 | "ancestor-str-dash": [],
345 | "bin": [
346 | "ItemId",
347 | "AncestorId",
348 | ],
349 | },
350 | "Chapters2": {
351 | "str": [],
352 | "str-dash": [],
353 | "ancestor-str": [],
354 | "ancestor-str-dash": [],
355 | "bin": [
356 | "ItemId",
357 | ],
358 | },
359 | "ItemValues": {
360 | "str": [],
361 | "str-dash": [],
362 | "ancestor-str": [],
363 | "ancestor-str-dash": [],
364 | "bin": [
365 | "ItemId",
366 | ],
367 | },
368 | "People": {
369 | "str": [],
370 | "str-dash": [],
371 | "ancestor-str": [],
372 | "ancestor-str-dash": [],
373 | "bin": [
374 | "ItemId",
375 | ],
376 | },
377 | "TypedBaseItems": {
378 | "str": [],
379 | "str-dash": [],
380 | "ancestor-str": [
381 | "TopParentId",
382 | "PresentationUniqueKey",
383 | "SeriesPresentationUniqueKey",
384 | ],
385 | "ancestor-str-dash": [
386 | "UserDataKey",
387 | "ExtraIds",
388 | ],
389 | "bin": [
390 | "guid",
391 | "ParentId",
392 | "SeasonId",
393 | "SeriesId",
394 | "OwnerId"
395 | ],
396 | },
397 | "UserDatas": {
398 | "str": [],
399 | "str-dash": [],
400 | "ancestor-str": [],
401 | "ancestor-str-dash": [
402 | "key",
403 | ],
404 | "bin": [],
405 | },
406 | "mediaattachments": {
407 | "str": [],
408 | "str-dash": [],
409 | "ancestor-str": [],
410 | "ancestor-str-dash": [],
411 | "bin": [
412 | "ItemId",
413 | ],
414 | },
415 | "mediastreams": {
416 | "str": [],
417 | "str-dash": [],
418 | "ancestor-str": [],
419 | "ancestor-str-dash": [],
420 | "bin": [
421 | "ItemId",
422 | ],
423 | },
424 | },
425 | },
426 | {
427 | "source": source_root / "data/playback_reporting.db",
428 | "target": "auto-existing", # If you used "auto" in todo_list_paths, leave this on "auto-existing". Otherwise specify same path.
429 | "replacements": {"oldids": "newids"}, # Will be auto-generated during the migration.
430 | "tables": {
431 | "PlaybackActivity": {
432 | "str": [],
433 | "str-dash": [],
434 | "ancestor-str": [
435 | "ItemId",
436 | ],
437 | "ancestor-str-dash": [],
438 | "bin": [],
439 | },
440 | },
441 | },
442 | ]
443 |
444 |
445 | # Since library.db will be needed throughout the process, its location is stored
446 | # here once it's been moved and updated with the new paths.
447 | library_db_target_path = Path()
448 | library_db_source_path = Path()
449 |
450 |
451 | # Similarly, the IDs are used in "hard-to-reach" places and are thus global, too.
452 | ids = dict()
453 |
454 |
455 | # Custom print function that prints to both the console as well as to a log file
456 | logging_newline = False
457 | def print_log(*args, **kwargs):
458 | global log_file, logging_newline
459 | print(*args, **kwargs)
460 |
461 | # Each new line gets a timestamp. That requires tracking of (previous)
462 | # line endings though. This is not perfect, but perfectly fine for this
463 | # script.
464 | dt = ""
465 | if logging_newline:
466 | dt = "[" + datetime.datetime.now().isoformat(sep=" ") + "] "
467 | if kwargs.get("end", "\n") == "\n":
468 | logging_newline = True
469 | else:
470 | logging_newline = False
471 | with open(log_file, "a", encoding="utf-8") as f:
472 | print(dt, *args, **kwargs, file=f)
473 |
474 |
475 | # Recursively replace all paths in "d" which can be
476 | # * a path object
477 | # * a path string
478 | # * a dictionary (only values are checked, no keys).
479 | # * a list
480 | # * any nested structure of the above.
481 | # * anything else is returned unmodified.
482 | # Returns the (un)modified object as well as how many items have been modified or ignored.
483 | def recursive_root_path_replacer(d, to_replace: dict):
484 | modified, ignored = 0, 0
485 | if type(d) is dict:
486 | for k, v in d.items():
487 | d[k], mo, ig = recursive_root_path_replacer(v, to_replace)
488 | modified += mo
489 | ignored += ig
490 | elif type(d) is list:
491 | for i, e in enumerate(d):
492 | d[i], mo, ig = recursive_root_path_replacer(e, to_replace)
493 | modified += mo
494 | ignored += ig
495 | elif type(d) is str or isinstance(d, pathlib.PurePath):
496 | try:
497 | p = Path(d)
498 | except:
499 | # This actually doesn't occur I think; Path() can pretty much convert any string into a Path
500 | # object (which is equivalent to saying it doesn't have any restrictions for filenames).
501 | ignored += 1
502 | else:
503 | found = False
504 | for src, dst in to_replace.items():
505 | if p.is_relative_to(src):
506 | # This filters out all the "garbage" paths that actually were no paths to begin with
507 | # and of course all the paths that are actually not relative to the src, dst couple
508 | # currently checked.
509 | p = dst / p.relative_to(src)
510 | # I guess 99% of the users won't migrate _to_ windows but the script could generate
511 | # \ paths anyways.
512 | # p.as_posix() makes sure that we always get a string with "/". Otherwise, on windows,
513 | # str(p) would automatically return "\" paths.
514 | d = p.as_posix().replace("/", to_replace["target_path_slash"])
515 | found = True
516 | break
517 | if found:
518 | modified += 1
519 | else:
520 | ignored += 1
521 | # No need to consider all the Path("sometext") objects. This might not be 100%
522 | # accurate, but it eliminates 99.9999% of the false-positives. This output is
523 | # after all only to give you a hint whether you missed a path.
524 | # Also exclude URLs. Btw: pathlib can be quite handy for messing with URLs.
525 | if len(p.parents) > 1 \
526 | and not d.startswith("https:") \
527 | and not d.startswith("http:") \
528 | and not to_replace.get("log_no_warnings", False):
529 | print_log(f"No entry for this (presumed) path: {d}")
530 | return d, modified, ignored
531 |
532 |
533 | # Almost the same as recursive_root_path_replacer but for replacing id parts somewhere in
534 | # the paths including file names (can't use "is_relative_to" for checking).
535 | # ID paths usually have the format '.../83/833addde992893e93d0572907f8b4cad/...'. It's
536 | # important to note and change that parent folder with the firs byte of the id, too.
537 | # Sometimes the parent folder is just single digit. This code handles any subsring that
538 | # starts at the beginning of the id string.
539 | def recursive_id_path_replacer(d, to_replace: dict):
540 | modified, ignored = 0, 0
541 | if type(d) is dict:
542 | for k, v in d.items():
543 | d[k], mo, ig = recursive_id_path_replacer(v, to_replace)
544 | modified += mo
545 | ignored += ig
546 | elif type(d) is list:
547 | for i, e in enumerate(d):
548 | d[i], mo, ig = recursive_id_path_replacer(e, to_replace)
549 | modified += mo
550 | ignored += ig
551 | elif type(d) is str or isinstance(d, pathlib.PurePath):
552 | try:
553 | p = Path(d)
554 | except:
555 | # This actually doesn't occur I think; Path() can pretty much convert any string into a Path
556 | # object (which is equivalent to saying it doesn't have any restrictions for filenames).
557 | ignored += 1
558 | else:
559 | found = False
560 |
561 | src, dst = "", ""
562 |
563 | if set(p.stem).issubset(set("0123456789abcdef-")):
564 | dst = to_replace.get(p.stem, "")
565 | if dst:
566 | found = True
567 | p = p.with_stem(dst)
568 |
569 | if not found:
570 | for part in p.parts[:-1]:
571 | # Check if it can actually be an ID. If so, look it up (which is expensive).
572 | if set(part).issubset(set("0123456789abcdef-")):
573 | src = part
574 | dst = to_replace.get(part, "")
575 | if dst:
576 | break
577 | if dst:
578 | found = True
579 | q = Path()
580 | # Find folder as path object that needs to be changed
581 | q = p
582 | while p.name != src:
583 | p = p.parent
584 | # q becomes the part relative to the now determined p part (with p.stem = id)
585 | q = q.relative_to(p)
586 | p = p.with_name(dst)
587 |
588 | # Check if the parent folder starts with byte(s) from the id
589 | if src.startswith(p.parent.name):
590 | # If so, move the already replaced part from p to q
591 | q = p.name / q
592 | p = p.parent
593 | # Replace required number of bytes
594 | p = p.with_name(dst[:len(p.name)])
595 |
596 | # Merge q and p back together
597 | p = p / q
598 | if found:
599 | modified += 1
600 | # I guess 99% of the users won't migrate _to_ windows but the script could generate
601 | # \ paths anyways.
602 | # p.as_posix() makes sure that we always get a string with "/". Otherwise, on windows,
603 | # str(p) would automatically return "\" paths.
604 | d = p.as_posix().replace("/", to_replace["target_path_slash"])
605 | else:
606 | ignored += 1
607 | # Unlike recursive_root_path_replacer, there is no need to warn the user about
608 | # potential paths that haven't been altered. In case you suspect that something is
609 | # overlooked, check out jellyfin_id_scanner.py.
610 | # ignored is purely maintained for signature compatibility with recursive_root_path_replacer.
611 | return d, modified, ignored
612 |
613 |
614 | def update_db_table(
615 | file,
616 | replace_dict,
617 | replace_func,
618 | table,
619 | path_columns=(),
620 | json_columns=(),
621 | jf_image_columns=(),
622 | preview=False
623 | ):
624 | # Initialize local variables
625 | rows_count, modified, ignored = 0, 0, 0
626 |
627 | # Initialize sqlite3 objects
628 | con = sqlite3.connect(file)
629 | cur = con.cursor()
630 |
631 | # If only one item has been specified, convert it to a list with one item instead.
632 | if type(path_columns) not in (tuple, set, list):
633 | path_columns = [path_columns]
634 | if type(json_columns) not in (tuple, set, list):
635 | json_columns = [json_columns]
636 | if type(jf_image_columns) not in (tuple, set, list):
637 | jf_image_columns = [jf_image_columns]
638 |
639 | # This index will be used to separate the json from the path columns in the cur.execute
640 | # result further below.
641 | json_stop = len(json_columns)
642 | path_stop = json_stop + len(path_columns)
643 |
644 | # For the sql query the desired row names should be enclosed in ` ` and comma separated.
645 | # It's important to note that the json columns come first, followed by the path columns
646 | columns = ", ".join([f"`{e}`" for e in list(json_columns) + list(path_columns)] + list(jf_image_columns))
647 |
648 | # Query the unique IDs of all rows. Note: we cannot iterate over the rows using
649 | # for row in cur.execute(get rows)
650 | # because the rows are modified by the loop, which breaks that iterator. Hence
651 | # the solution with reading all row ids and iterating over them instead.
652 | # Note: The cur.execute yields tuples with all the columns queried. Which means that
653 | # the array below actually contains _tuples_ with the id. This is however desirable
654 | # in our case; see below where id is used.
655 | todo = [rowid for rowid in cur.execute(f"SELECT `rowid` FROM `{table}`") if rowid[0]]
656 | rows_count = len(todo)
657 | t = time()
658 | for progress, id in enumerate(todo):
659 | # Print the progress every second. Note: this is the only usage of the "progress" variable.
660 | now = time()
661 | if now - t > 1:
662 | print_log(f"Progress: {progress} / {rows_count} rows")
663 | t = now
664 |
665 | # Query the columns we want to check/modify of the current row (selected by id).
666 | # Since the id is a binary object, it's not directly included in the f-string.
667 | # The cur.execute expects as second argument a _tuple_ with as many elements as
668 | # there are ? characters in the query string. This is the reason why we kept the
669 | # IDs as tuple. The only other place where this id is used is in the update query
670 | # at the end of the loop which requires - just like here - a tuple.
671 | row = [r for r in cur.execute(f"SELECT {columns} FROM `{table}` WHERE `rowid` = ?", id)]
672 | # This _should_ not occur, but I think I have seen it happen rarely. Safe is safe.
673 | if len(row) != 1:
674 | print_log(f"Error with rowid {id}! Resulted in {len(row)} rows instead of 1. Skipping.")
675 | continue
676 | # cur.execute returns a 2D tuple, containing all rows matching the query, and then
677 | # in each row the selected columns. We only selected a single row, hence row[0] is
678 | # all we care about (and all there is, see error handling above).
679 | # Secondly we want row to be modifiable, hence the conversion to a list.
680 | # list(row[0]) would btw return a list with 1 element: the tuple of the columns.
681 | row = [e for e in row[0]]
682 |
683 | # result has the structure {column_name: updated_data} which makes it very easy to build
684 | # the update query at the end.
685 | result = dict()
686 |
687 | # It's important to note that the tuple from cur.execute contains the columns _in the order
688 | # of the query string_. Therefore, we can separate json and path entries like this.
689 | jsons = row[:json_stop]
690 | paths = row[json_stop:path_stop]
691 | jf_imgs = row[path_stop:]
692 | for i, data in enumerate(jsons):
693 | if data:
694 | # There are numerous rows that have empty columns which would result in an error
695 | # from json.loads. Just skip them
696 | data = json.loads(data)
697 | data, mo, ig = replace_func(data, replace_dict)
698 | modified += mo
699 | ignored += ig
700 | result[json_columns[i]] = json.dumps(data)
701 | for i, path in enumerate(paths):
702 | # One could also skip the empty objects here, but recursive_path_replacer handles them
703 | # just fine (leaves them untouched).
704 | path, mo, ig = replace_func(path, replace_dict)
705 | modified += mo
706 | ignored += ig
707 | result[path_columns[i]] = path
708 | for i, imgs in enumerate(jf_imgs):
709 | # Jellyfin Image Metadata. Some DB entries look like this:
710 | # %MetadataPath%\library\71\71d037e6e74015a5a6231ce1b7912acf\poster.jpg*637693022742223153*Primary*198*198*eJC5#hK#Dj9GR/V@j]xuX8NG0x+xgN%MxaX7spNGnitQ$kK0wyV@Rj # noqa
711 | # Yeah. That's a path and some other data within the same string, separated by *. More specifically:
712 | # path * last modified date * image type * width * height * blur hash
713 | # where width, height, blur hash are apparently optional.
714 | # In theory, the * could occur as normal character within regular paths but it's unlikely.
715 | # Oh, and did I mention that such strings can contain multiple of these structures separated by a | ?
716 | # Source (Jellyfin Server 10.7.7): DeserializeImages, AppendItemImageInfo:
717 | # https://github.com/jellyfin/jellyfin/blob/045761605531f98c55f379ac9eb5b5b6004ef670/Emby.Server.Implementations/Data/SqliteItemRepository.cs#L1118 # noqa
718 | if not imgs:
719 | continue
720 | imgs = imgs.split("|")
721 | for j, img_properties in enumerate(imgs):
722 | if not img_properties:
723 | continue
724 | img_properties = img_properties.split("*")
725 | # path = first property
726 | img_properties[0], mo, ig = replace_func(img_properties[0], replace_dict)
727 | imgs[j] = "*".join(img_properties)
728 | modified += mo
729 | ignored += ig
730 | imgs = "|".join(imgs)
731 | result[jf_image_columns[i]] = imgs
732 |
733 | # Similar to the initial query we construct a comma separated list of the columns, only this
734 | # time we write
735 | # `columnname` = ?
736 | # While the new values are all strings, the question mark avoids any issues with handling
737 | # backslashes etc. The library offers an easy, built-in way to do it so there's no reason
738 | # to mess with it myself.
739 | # Note that this relies on result.keys() and result.values() returning the entries in the
740 | # same order (which is guaranteed).
741 | # Note: it can happen that no changes are made at all. In this case we can abort here and
742 | # go for the next job from the todo_list.
743 | if not result:
744 | continue
745 | keys = ", ".join([f"`{k}` = ?" for k in result.keys()])
746 | query = f"UPDATE `{table}` SET {keys} WHERE `rowid` = ?"
747 |
748 | # The query has a question mark for each updated column plus one for the id to identify
749 | # the correct row.
750 | args = tuple(result.values()) + id
751 | try:
752 | cur.execute(query, args)
753 | except Exception as e:
754 | # This was mainly for debugging purposes and shouldn't be reached anymore. Doesn't
755 | # hurt to have it though.
756 | print_log("Error:", e)
757 | print_log("Query:", query)
758 | print_log("Args: ", args)
759 | print_log(e)
760 | exit()
761 | else:
762 | if cur.rowcount < 1:
763 | # This was mainly for debugging purposes and shouldn't be reached anymore.
764 | # Doesn't hurt to have it though.
765 | print_log("No data modified!")
766 | print_log("Query:", query)
767 | print_log("Args: ", args)
768 | exit()
769 | print_log(f"Processed {rows_count} rows in table {table}. ")
770 | print_log(f"{modified} paths have been modified.")
771 |
772 | # Once again, this came from the development and is not required anymore, especially
773 | # since by default the script is working on copies of the original files.
774 | if not preview:
775 | # Write the updated database back to the file.
776 | con.commit()
777 | con.close()
778 |
779 |
780 | # Walks through an XML file and checks *all* entries.
781 | # WARNING: The documentation of this parser explicitly mentions that it's not hardened against
782 | # known XML vulnerabilities. It is NOT suitable for unknown/unsafe XML files. Shouldn't be an
783 | # issue here though.
784 | def update_xml(file: Path, replace_dict: dict, replace_func) -> None:
785 | modified, ignored = 0, 0
786 | tree = ET.parse(file)
787 | root = tree.getroot()
788 | for el in root.iter():
789 | # Exclude a few tags known to contain no paths.
790 | # biography, outline: These often contain lots of text (= slow to process) and generate
791 | # false-positives for the missed path detection (see recursive_root_path_replacer)
792 | if el.tag in ("biography", "outline"):
793 | continue
794 | el.text, mo, ig = replace_func(el.text, replace_dict)
795 | modified += mo
796 | ignored += ig
797 | print_log(f"Processed {ignored + modified} elements. {modified} paths have been modified.")
798 | tree.write(file) # , encoding="utf-8")
799 |
800 |
801 | # Remember if the user wants to ignore all future warnings.
802 | user_wants_inplace_warning = True
803 |
804 |
805 | def get_target(
806 | source: Path,
807 | target: Path,
808 | replacements: dict,
809 | no_log: bool = False,
810 | ) -> Path:
811 | # Not the cleanest solution for remembering it between function calls but good enough here.
812 | global user_wants_inplace_warning
813 | # global all_path_changes
814 |
815 | source = Path(source)
816 | target = Path(target)
817 |
818 | skip_copy = False
819 |
820 | # "auto" means the target path is generated by the same path replacement dictionary that's
821 | # also used to update all the path strings.
822 | # In this case we don't care about the stats returned by recursive_path_replacer, hence
823 | # the variable names.
824 | if len(target.parts) == 1 and target.name.startswith("auto"):
825 | if target.name == "auto-existing":
826 | skip_copy = True
827 | original_source = original_root / source.relative_to(source_root)
828 | target, idgaf1, idgaf2 = recursive_root_path_replacer(original_source, to_replace=replacements)
829 | target, idgaf1, idgaf2 = recursive_root_path_replacer(target, to_replace=fs_path_replacements)
830 | target = Path(target)
831 | if not target.is_absolute():
832 | if target.is_relative_to("/"):
833 | # Otherwise the line below will make target relative to the _root_ of target_root
834 | # instead of relative to target_root.
835 | target = target.relative_to("/")
836 | target = target_root / target
837 |
838 | # If source and target are the same there are two possibilities:
839 | # 1. The user actually wants to work on the given source files; maybe he already created
840 | # a copy and directly pointed this script towards that copy.
841 | # 2. The user forgot that they shouldn't touch the original files.
842 | # 3. Something's wrong with the path replacement dict.
843 | # In any cases, the user is notified and can decide whether he wants to continue this time,
844 | # all the remaining times, too, or abort.
845 | #
846 | # Program: Are you sure? User: I don't know [yet]
847 | usure = "idk"
848 | if source == target:
849 | if user_wants_inplace_warning:
850 | while usure not in "yna":
851 | usure = input("Warning! Working on original file! Continue? [Y]es, [N]o, [A]lways ")
852 | # j is for the german "ja" which means yes.
853 | usure = usure[0].lower().replace("j", "y")
854 | if usure == "n":
855 | print_log("Skipping this file. If you want to abort the whole process, stop the script"
856 | "with CTRL + C.")
857 | target = None
858 | elif usure == "a":
859 | # Don't warn about this anymore.
860 | user_wants_inplace_warning = False
861 | elif not skip_copy:
862 | if not target.parent.exists():
863 | target.parent.mkdir(parents=True)
864 | if not no_log:
865 | print_log("Copying...", target, end=" ")
866 | copy(source, target)
867 | if not no_log:
868 | print_log("Done.")
869 | return target
870 |
871 |
872 | def process_file(
873 | source: Path,
874 | target: Path,
875 | replacements: dict,
876 | replace_func,
877 | tables:dict = None,
878 | copy_only: bool = False,
879 | no_log: bool = False,
880 | ) -> None:
881 | if tables is None:
882 | tables = dict()
883 |
884 | # What do you want me to do with no input?
885 | if not target:
886 | return
887 |
888 | # Files only.
889 | if target.is_dir():
890 | return
891 |
892 | if not no_log:
893 | print_log("Processing", target)
894 |
895 | if copy_only:
896 | # No need to do any further checks.
897 | return
898 | elif target.suffix == ".db":
899 | # If it's "library.db", save it for later (see comment at declaration):
900 | if target.name == "library.db":
901 | global library_db_source_path, library_db_target_path
902 | library_db_source_path = source
903 | library_db_target_path = target
904 | # sqlite file. In this case table specifies which tables within that file have columns to check.
905 | # Iterate over those.
906 | for table, kwargs in tables.items():
907 | print_log("Processing table", table)
908 | # The remaining function arguments (**kwards) contain the details about the columns to process.
909 | # See update_db_table and/or the todo_list.
910 | update_db_table(file=target, replace_dict=replacements, replace_func=replace_func, table=table, **kwargs)
911 | elif target.suffix == ".xml" or target.suffix == ".nfo":
912 | update_xml(file=target, replace_dict=replacements, replace_func=replace_func)
913 | elif target.suffix == ".mblink":
914 | # .mblink files only contain a path, nothing else.
915 | with open(target, "r", encoding="utf-8") as f:
916 | path = f.read()
917 | path, modified, ignored = replace_func(path, replacements)
918 | print_log(f"Processed {modified + ignored} paths, {modified} paths have been modified.")
919 | with open(target, "w", encoding="utf-8") as f:
920 | f.write(path)
921 | elif target.suffix == ".json":
922 | # There are also json files with the ending .js but I haven't found any with paths.
923 | # Load the file by the json module (resulting in a dict or list object) and process
924 | # them by recursive_path_replacer which handles these structures.
925 | with open(target, "r", encoding="utf-8") as f:
926 | j = json.load(f)
927 | j, modified, ignored = replace_func(j, replacements)
928 | print_log(f"Processed {modified + ignored} paths, {modified} paths have been modified.")
929 | with open(target, "w", encoding="utf-8") as f:
930 | # indent 2 seems to be the default formatting for jellyfin json files.
931 | json.dump(j, f, indent=2)
932 |
933 | # If we're updating path ids we also need to check the paths of the files themselves
934 | # and move them if they're relative to a path.
935 | # This obviously leaves empty folders behind, which are cleaned up afterwards.
936 | if replace_func == recursive_id_path_replacer:
937 | source = target
938 | target, modified, ignored = recursive_id_path_replacer(source, replacements)
939 | if modified:
940 | print_log("Changing ID in filepath: ->", target)
941 | target = Path(target)
942 | target.parent.mkdir(parents=True, exist_ok=True)
943 | source.replace(target)
944 |
945 |
946 | # Processes the todo_list.
947 | # It handles potential wildcards in the file paths and keeps track
948 | # which files have already been processed. This allows you to have an
949 | # automatic, wildcard copy in your todo_list that just copies the files
950 | # to the (modified) destinations without processing them and without
951 | # modifying those that have already been copied _and_ modified.
952 | # Obviously this requires you to have the files that need processing
953 | # first in the todo_list and only then the wildcard copies.
954 | #
955 | # lst: job list
956 | # process_func: function to apply to jobs of lst.
957 | # replace_func: function used by process_func to do the replacing of paths, ...
958 | def process_files(lst: list, process_func, replace_func, path_replacements):
959 | done = set()
960 | for job in lst:
961 | if "no_log" not in job:
962 | job["no_log"] = False
963 | source = job["source"]
964 | print_log(f"Current job from todo_list: {source}")
965 | if "*" in str(source):
966 | # Path has wildcards, process all matching files.
967 | #
968 | # Ironically Path.glob can't handle Path objects, hence the need
969 | # to convert them to a string...
970 | # It is expected that all these paths are relative to source_root.
971 | source = source.relative_to(source_root)
972 | for src in source_root.glob(str(source)):
973 | if src.is_dir():
974 | continue
975 | if src in done:
976 | # File has already been processed by this script.
977 | continue
978 | done.add(src)
979 |
980 | target = get_target(
981 | source=src,
982 | target=job["target"],
983 | replacements=path_replacements,
984 | no_log=job["no_log"],
985 | )
986 |
987 | # pass the job as is but with non-wildcard source path.
988 | process_func(
989 | replace_func=replace_func,
990 | source=src,
991 | target=target,
992 | **{k: v for k, v in job.items() if k not in ("source", "target")},
993 | )
994 | else:
995 | # No wildcards, process the path directly - if it hasn't already
996 | # been processed.
997 | if source in done:
998 | continue
999 | done.add(source)
1000 |
1001 | target = get_target(
1002 | source=source,
1003 | target=job["target"],
1004 | replacements=path_replacements,
1005 | no_log=job["no_log"],
1006 | )
1007 |
1008 | process_func(
1009 | replace_func=replace_func,
1010 | source=source,
1011 | target=target,
1012 | **{k: v for k, v in job.items() if k not in ("source", "target")},
1013 | )
1014 | print_log("")
1015 |
1016 |
1017 | # Note: The .NET .Unicode method encodes as UTF16 little endian:
1018 | # https://docs.microsoft.com/en-us/dotnet/api/system.text.encoding.unicode?view=net-6.0
1019 | def get_dotnet_MD5(s: str):
1020 | return hashlib.md5(s.encode("utf-16-le")).digest()
1021 |
1022 |
1023 | # Derived/copied from update_db_table. I couldn't see a good way to do this without
1024 | # copying. The data structures and processing are too different for path and id jobs.
1025 | # Note: kwargs is due to how process_files works. It passes a lot of stuff from the
1026 | # job list that's not needed here.
1027 | def update_db_table_ids(
1028 | source,
1029 | target,
1030 | tables,
1031 | preview=False,
1032 | **kwargs
1033 | ):
1034 | global ids
1035 |
1036 | print_log("Updating Item IDs in database... ")
1037 |
1038 | # Initialize sqlite3 objects
1039 | con = sqlite3.connect(target)
1040 | cur = con.cursor()
1041 |
1042 | updated_ids_count = 0
1043 | # That's a very nested loop and could probably be written more efficiently using
1044 | # multiprocessing and more advanced sqlite queries.
1045 | for table, columns_by_id_type in tables.items():
1046 | for id_type, columns in columns_by_id_type.items():
1047 | for column in columns:
1048 | print_log(f"Updating {column} IDs in table {table}...")
1049 | # See comment about iterating over rows while modifying them in update_db_table.
1050 | rows = [r for r in cur.execute(f"SELECT DISTINCT `{column}` from `{table}`")]
1051 | progress = 0
1052 | rowcount = len(rows)
1053 | t = time()
1054 | for old_id, in rows:
1055 | progress += 1
1056 | # Print the progress every second. Note: this is the only usage of the "progress" variable.
1057 | now = time()
1058 | if now - t > 1:
1059 | print_log(f"Progress: {progress} / {rowcount} rows")
1060 | t = now
1061 | if old_id in ids[id_type]:
1062 | new_id = ids[id_type][old_id]
1063 | try:
1064 | cur.execute(f"UPDATE `{table}` SET `{column}` = ? WHERE `{column}` = ?", (new_id, old_id))
1065 | except sqlite3.IntegrityError:
1066 | col_names = [x[0] for x in cur.execute(f"SELECT name FROM PRAGMA_TABLE_INFO('{table}')")]
1067 | rows = [x for x in cur.execute(f"SELECT * FROM `{table}` WHERE `{column}` = ?", (old_id,))]
1068 | rows = [dict(zip(col_names, row)) for row in rows]
1069 | print_log(f"Encountered {len(rows)} duplicated entries")
1070 | for i, row in enumerate(rows):
1071 | print_log(f"Deleting ({i+1}/{len(rows)}): ", row)
1072 | cur.execute(f"DELETE FROM `{table}` WHERE `{column}` = ?", (old_id,))
1073 | updated_ids_count += 1
1074 |
1075 | # Once again, this came from the development and is not required anymore, especially
1076 | # since by default the script is working on copies of the original files.
1077 | if not preview:
1078 | # Write the updated database back to the file.
1079 | con.commit()
1080 | con.close()
1081 | print_log(f"{updated_ids_count} IDs updated.")
1082 |
1083 |
1084 | def get_ids():
1085 | global library_db_target_path, ids
1086 |
1087 | con = sqlite3.connect(library_db_target_path)
1088 | cur = con.cursor()
1089 |
1090 | id_replacements_bin = dict()
1091 | for guid, item_type, path in cur.execute("SELECT `guid`, `type`, `Path` FROM `TypedBaseItems`"):
1092 | if not path or path.startswith("%"):
1093 | continue
1094 |
1095 | # Source: https://github.com/jellyfin/jellyfin/blob/7e8428e588b3f0a0574da44081098c64fe1a47d7/Emby.Server.Implementations/Library/LibraryManager.cs#L504 # noqa
1096 | new_guid = get_dotnet_MD5(item_type + path)
1097 | # Omit IDs that haven't changed at all. Happens if not _all_ paths are modified
1098 | if new_guid != guid:
1099 | id_replacements_bin[guid] = new_guid
1100 |
1101 | ### Adapted from jellyfin_id_scanner
1102 | id_replacements_str = {bid2sid(k): bid2sid(v) for k, v in id_replacements_bin.items()}
1103 | id_replacements_str_dash = {sid2did(k): sid2did(v) for k, v in id_replacements_str.items()}
1104 | id_replacements_ancestor_str = {convert_ancestor_id(k): convert_ancestor_id(v) for k, v in id_replacements_str.items()}
1105 | id_replacements_ancestor_bin = {sid2bid(k): sid2bid(v) for k, v in id_replacements_ancestor_str.items()}
1106 | id_replacements_ancestor_str_dash = {sid2did(k):sid2did(v) for k, v in id_replacements_ancestor_str.items()}
1107 |
1108 | ids = {
1109 | "bin": id_replacements_bin,
1110 | "str": id_replacements_str,
1111 | "str-dash": id_replacements_str_dash,
1112 | "ancestor-bin": id_replacements_ancestor_bin,
1113 | "ancestor-str": id_replacements_ancestor_str,
1114 | "ancestor-str-dash": id_replacements_ancestor_str_dash,
1115 | }
1116 | ### End of adapted code
1117 |
1118 | # Check for collisions between old and new ids in both the normal and ancestor format.
1119 | # If there are collisions, get the (new) filepaths causing them
1120 | uniques = set()
1121 | duplicates = list()
1122 | for id in id_replacements_str.values():
1123 | if id in uniques:
1124 | duplicates.append(id)
1125 | else:
1126 | uniques.add(id)
1127 |
1128 | # if there are duplicates, find the matching old_ids to query the lines from the database
1129 | if duplicates:
1130 | old_ids = []
1131 | for k, v in id_replacements_str.items():
1132 | if v in duplicates:
1133 | old_ids.append(sid2bid(k))
1134 |
1135 | duplicates_new = [next(cur.execute("SELECT `guid`, `Path` FROM `TypedBaseItems` WHERE `guid` = ?", (guid,))) for guid in old_ids]
1136 | # also fetch the old paths for better understanding/debugging
1137 | con.close()
1138 | con = sqlite3.connect(library_db_source_path)
1139 | cur = con.cursor()
1140 | duplicates_old = [next(cur.execute("SELECT `guid`, `Path` FROM `TypedBaseItems` WHERE `guid` = ?", (guid,))) for guid in old_ids]
1141 | duplicates_old = dict(duplicates_old)
1142 | con.close()
1143 |
1144 | print_log(f"Warning! {len(duplicates)} duplicates detected within new ids. This indicates that you're "
1145 | f"merging media files from different directories into fewer ones. If that's the case for all the "
1146 | f"collisions listed below, you can likely ignore this warning, otherwise recheck your path settings. "
1147 | f"IMPORTANT: The duplicated entries will be removed from the database. You got a backup of the "
1148 | f"database, right?")
1149 | print_log("Duplicates: ")
1150 | for id, newpath in duplicates_new:
1151 | print_log(f" Item ID: {bid2sid(id)}, Paths (old -> new): {duplicates_old[id]} -> {newpath}")
1152 | input("Press Enter to continue or CTRL+C to abort. ")
1153 |
1154 | return ids
1155 |
1156 |
1157 | def update_ids():
1158 | return
1159 |
1160 |
1161 | def jf_date_str_to_python_ns(s: str):
1162 | # Python datetime has only support for microseconds because of resolution
1163 | # problems. To convert from a date+time to ticks, the fractional seconds
1164 | # part doesn't matter anyway (it remains the same). Hence, it's cut off
1165 | # and added back later.
1166 | subseconds = "0"
1167 | if "." in s:
1168 | s, subseconds = s.rsplit(".", 1)
1169 | # In case subseconds has a higher resolution than 100ns and/or additional
1170 | # information (f.ex. timezone, which is known to be UTC+00:00 for jellyfin),
1171 | # Strip all of it.
1172 | # Add trailing zeros til the ns digit, then convert to int, and we have ns.
1173 | subseconds = int(subseconds.split("+")[0].rstrip(ascii_letters).ljust(9, "0"))
1174 | # Add explicit information about the timezone (UTC+00:00)
1175 | s += "+00:00"
1176 | t = int(datetime.datetime.fromisoformat(s).timestamp())
1177 | # Convert to ns
1178 | t *= 1000000000
1179 | t += subseconds
1180 | return t
1181 |
1182 |
1183 | # Convert a _python_ timestamp (float seconds since epoch, which is os dependent)
1184 | # to a ISO like date string as found in the jellyfin database. I have no idea
1185 | # if this works for all OS'es in all timezones. Very likely not but that whole
1186 | # topic is about as much of a mess as jellyfin's databases. If you got any issues,
1187 | # I'm sorry. If you find a solution, them, please let me know!
1188 | def get_datestr_from_python_time_ns(time_ns: int):
1189 | # Datetime has no support for sub-microsecond resolution (which is required here).
1190 | # Doesn't matter anyway, we can add the whole sub-second part afterwards.
1191 | time_s = time_ns // 1000000000
1192 | time_frac_s_100ns = (time_ns // 100) % 10000000
1193 | timestamp = datetime.datetime.utcfromtimestamp(time_s).isoformat(sep=" ", timespec="seconds")
1194 | # Add back the sub-seconds part and the UTC time zone
1195 | timestamp += "." + str(time_frac_s_100ns).rjust(7, "0").rstrip("0") + "Z"
1196 | return timestamp
1197 |
1198 |
1199 | def delete_empty_folders(dir:str):
1200 | dir = Path(dir)
1201 |
1202 | done = False
1203 | while not done:
1204 | done = True
1205 | for p in dir.glob("**"):
1206 | if not list(p.iterdir()):
1207 | print_log("Removing empty folder", p)
1208 | p.rmdir()
1209 | done = False
1210 |
1211 |
1212 | def update_file_dates():
1213 | global library_db_target_path, fs_path_replacements
1214 |
1215 | print_log("Updating file dates... Note: Reading file dates seems to be quite slow. "
1216 | "This will take a couple minutes")
1217 |
1218 | con = sqlite3.connect(library_db_target_path)
1219 | cur = con.cursor()
1220 |
1221 | rows = [r for r in cur.execute("SELECT `rowid`, `Path`, `DateCreated`, `DateModified` FROM `TypedBaseItems`")]
1222 |
1223 | progress = 0
1224 | rowcount = len(rows)
1225 | t = time()
1226 |
1227 | for rowid, target, date_created, date_modified in rows:
1228 | progress += 1
1229 | # Print the progress every second. Note: this is the only usage of the "progress" variable.
1230 | now = time()
1231 | if now - t > 1:
1232 | print_log(f"Progress: {progress} / {rowcount} rows")
1233 | t = now
1234 |
1235 | if not target:
1236 | continue
1237 | # Determine file path as seen by this script (see fs_path_replacements for details)
1238 | # Code taken from get_target
1239 | target, idgaf1, idgaf2 = recursive_root_path_replacer(target, to_replace=fs_path_replacements)
1240 | target = Path(target)
1241 | if not target.is_absolute():
1242 | if target.is_relative_to("/"):
1243 | # Otherwise the line below will make target relative to the _root_ of target_root
1244 | # instead of relative to target_root.
1245 | target = target.relative_to("/")
1246 | target = target_root / target
1247 | # End of code taken from get_target
1248 |
1249 | if not target.exists():
1250 | print_log("File doesn't seem to exist; can't update its dates in the database: ", target)
1251 | continue
1252 |
1253 | date_created_ns = jf_date_str_to_python_ns(date_created)
1254 | date_modified_ns = jf_date_str_to_python_ns(date_modified)
1255 |
1256 | if date_created_ns >= 0 and date_modified_ns >= 0:
1257 | continue
1258 |
1259 | filestats = os.stat(target)
1260 |
1261 | if date_created_ns < 0:
1262 | new_date_created = get_datestr_from_python_time_ns(filestats.st_ctime_ns)
1263 | cur.execute("UPDATE `TypedBaseItems` SET `DateCreated` = ? WHERE `rowid` = ?",
1264 | (new_date_created, rowid))
1265 | if date_modified_ns < 0:
1266 | new_date_modified = get_datestr_from_python_time_ns(filestats.st_mtime_ns)
1267 | cur.execute("UPDATE `TypedBaseItems` SET `DateModified` = ? WHERE `rowid` = ?",
1268 | (new_date_modified, rowid))
1269 |
1270 | con.commit()
1271 | print_log("Done.")
1272 |
1273 |
1274 | if __name__ == "__main__":
1275 | print_log("")
1276 | print_log("Starting Jellyfin Database Migration")
1277 |
1278 | ### Copy relevant files and adjust all paths to the new locations.
1279 | process_files(
1280 | todo_list_paths,
1281 | process_func=process_file,
1282 | replace_func=recursive_root_path_replacer,
1283 | path_replacements=path_replacements,
1284 | )
1285 |
1286 | ### Update IDs
1287 | # Generate IDs based on those new paths and save them in the global variable
1288 | get_ids()
1289 | # ID types occurring in paths (<- search for that to find another comment with more details if you missed it)
1290 | # Include/Exclude types (see get_ids) to specify which are used for looking through paths.
1291 | # Currently, all are included, just to be safe.
1292 | id_replacements_path = {**ids["ancestor-str"], **ids["ancestor-str-dash"], **ids["str"], **ids["str-dash"],
1293 | "target_path_slash": path_replacements["target_path_slash"]}
1294 |
1295 | # To (mostly) reuse the same functions from step 1, the replacements dict needs to be updated with
1296 | # id_replacements_path. It can't be replaced since it's also used to find the files (which uses the
1297 | # same source -> target processing/conversion as step 1). In theory this alters the process since
1298 | # the dict used to convert from source -> target is different, in reality, this is not an issue,
1299 | # since step 1 only processes the roots of the paths (which cannot be similar to anything in
1300 | # id_replacements_path).
1301 | for i, job in enumerate(todo_list_id_paths):
1302 | todo_list_id_paths[i]["replacements"] = id_replacements_path
1303 |
1304 | # Replace all paths with ids - both in the file system and within files.
1305 | process_files(
1306 | todo_list_id_paths,
1307 | process_func=process_file,
1308 | replace_func=recursive_id_path_replacer,
1309 | path_replacements={**path_replacements, **id_replacements_path},
1310 | )
1311 | # Clean up empty folders that may be left behind in the target directory
1312 | #delete_empty_folders(target_root)
1313 |
1314 | # Replace remaining ids.
1315 | process_files(
1316 | todo_list_ids,
1317 | process_func=update_db_table_ids,
1318 | replace_func=None,
1319 | path_replacements = path_replacements,
1320 | )
1321 |
1322 | # Finally, update the file dates in the db.
1323 | update_file_dates()
1324 |
1325 | print_log("")
1326 | print_log("Jellyfin Database Migration complete.")
1327 |
--------------------------------------------------------------------------------