├── .gitignore ├── LICENSE ├── README.md └── src ├── Dockerfile ├── JellyfinHandler.py ├── JellyfinUtil.py └── PinyinUtil.py /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled class file 2 | *.class 3 | 4 | # Log file 5 | *.log 6 | 7 | # BlueJ files 8 | *.ctxt 9 | 10 | # Mobile Tools for Java (J2ME) 11 | .mtj.tmp/ 12 | 13 | # Package Files # 14 | *.jar 15 | *.war 16 | *.nar 17 | *.ear 18 | *.zip 19 | *.tar.gz 20 | *.rar 21 | 22 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 23 | hs_err_pid* 24 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # jellyfin_pinyin 2 | 3 | Jellyfin 以及 Emby 标题拼音处理 支持客户端按拼音字母排序 4 | 5 | * 2.0 之后改成 python 代码实现 6 | 7 | # 使用说明 8 | docker 搜素 `wizzer/jellyfin_pinyin` 安装 9 | 10 | 启动服务时会自动运行(延迟10s),其后按配置的间隔时间周期性执行(执行时判断是否已处理,已处理则自动跳过) 11 | 12 | 13 | # docker 环境变量说明 14 | 15 | 变量名称 | 默认值 | 说明 16 | ----|------|---- 17 | URL | http://127.0.0.1:8096 | 服务器地址(末尾不加/) 18 | KEY | API KEY | Jellyfin-控制台-高级-API密钥 添加 19 | MEDIA | | 要扫描的媒体库名称以英文 , 分割,如 电影,动画 (删除此配置项则为扫描全部) 20 | TIME | 3600 | 周期扫描的时间间隔,单位秒 21 | 22 | * 特别注意,emby 的服务器地址为 http://127.0.0.1:8096/emby 23 | * 网络设置为 host,这样才可以访问服务地址 24 | 25 | 26 | # 编译说明(src 目录下执行) 27 | 28 | * `docker build -t wizzer/jellyfin_pinyin:v2.1_arm . --platform=linux/arm64` Docker打包发布(for arm) 29 | * `docker build -t wizzer/jellyfin_pinyin:v2.1 . --platform=linux/amd64` Docker打包发布 30 | * `docker build -t wizzer/jellyfin_pinyin:latest . --platform=linux/amd64` Docker发布latest版 31 | -------------------------------------------------------------------------------- /src/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM python:3.9.5-slim 2 | COPY . /app 3 | 4 | ENV TZ "Asia/Shanghai" 5 | ENV TIME 3600 6 | ENV URL "http://127.0.0.1:8096" 7 | ENV KEY "" 8 | ENV MEDIA "" 9 | RUN pip install pypinyin 10 | RUN pip install requests 11 | 12 | WORKDIR /app 13 | CMD ["python","/app/JellyfinHandler.py"] 14 | -------------------------------------------------------------------------------- /src/JellyfinHandler.py: -------------------------------------------------------------------------------- 1 | import os 2 | import json 3 | import time 4 | from PinyinUtil import PinyinUtil # 需要实现PinyinUtil 5 | from JellyfinUtil import JellyfinUtil # 需要实现JellyfinUtil 6 | import logging 7 | 8 | class JellyfinHandler: 9 | def __init__(self): 10 | self.log = logging.getLogger(__name__) 11 | self.domain = "" #http://10.10.10.10:8096 12 | self.key = "" #API KEY 13 | self.media = "" #需要处理的媒体库 14 | self.process_count = 0 15 | self.skip_count = 0 16 | self.time = 10 17 | self.user_id = "" 18 | 19 | def init(self): 20 | self.domain = os.getenv("URL", "http://127.0.0.1:8096") # 服务器地址 21 | self.key = os.getenv("KEY") # API KEY 22 | self.media = os.getenv("MEDIA", "") # 需要处理的媒体库 23 | self.time = int(os.getenv("TIME", "3600")) # 扫描间隔时间 24 | self.log.info(f"扫描媒体库: {self.media if self.media else '全部'}") 25 | 26 | if not self.domain: 27 | self.log.info("服务器地址未设置,使用默认地址 http://127.0.0.1:8096") 28 | else: 29 | self.log.info(f"服务器地址 {self.domain}") 30 | 31 | if not self.key: 32 | self.log.error("API KEY未设置") 33 | return 34 | 35 | # 延迟10秒执行,防止重启后Jellyfin服务未启动完成 36 | time.sleep(10) 37 | self.run() 38 | # 循环执行,每隔一段时间执行一次 39 | while True: 40 | time.sleep(self.time) 41 | self.run() 42 | 43 | 44 | def run(self): 45 | self.user_id = self.get_user_id() 46 | if not self.user_id: 47 | self.log.error("未获取到管理员用户") 48 | return 49 | 50 | views = self.get_views() 51 | medias = self.media.split(",") if self.media else [] 52 | for view in views: 53 | if not medias or view.get("Name") in medias: 54 | self.processed_view(view) 55 | 56 | def get_user_id(self): 57 | nut_map = JellyfinUtil.get_users(self.domain, self.key) 58 | if not nut_map: 59 | return None 60 | 61 | user_list = nut_map.get("Users", []) 62 | for user in user_list: 63 | if user.get("Policy", {}).get("IsAdministrator"): 64 | return user.get("Id") 65 | return None 66 | 67 | def get_views(self): 68 | nut_map = JellyfinUtil.get_views(self.domain, self.key, self.user_id) 69 | if not nut_map: 70 | self.log.error("未获取到媒体库") 71 | return [] 72 | 73 | return nut_map.get("Items", []) 74 | 75 | def render_items(self, items): 76 | folders = ["Folder", "Season", "CollectionFolder"] 77 | objects = ["Series", "Movie", "BoxSet", "Audio", "MusicAlbum", "MusicArtist", "Video", "Photo", "Episode"] 78 | 79 | for item in items: 80 | if item.get("Type") in folders: 81 | self.render_folder(item.get("Id"), item.get("CollectionType")) 82 | elif item.get("Type") in objects: 83 | item_detail = JellyfinUtil.get_item(self.domain, self.key, self.user_id, item.get("Id")) 84 | if not item_detail: 85 | self.log.error("服务器出错,请重启Jellyfin") 86 | return 87 | 88 | forced_sort_name = item_detail.get("ForcedSortName") 89 | pinyin = PinyinUtil.get_pingyin(item_detail.get("Name", "")) if item_detail.get("Name") else "" 90 | if pinyin and len(pinyin) > 50: 91 | pinyin = pinyin[:50] 92 | 93 | if forced_sort_name and pinyin == forced_sort_name: 94 | self.log.info(f"跳过 {item_detail.get('Name')}") 95 | self.skip_count += 1 96 | else: 97 | self.log.info(f"处理 {item_detail.get('Name')}") 98 | item_detail["ForcedSortName"] = pinyin 99 | item_detail["SortName"] = pinyin 100 | # emby 锁定字段,否则不生效 101 | # 判断self.domain路径是否包含emby字符串 102 | if "emby" in self.domain: 103 | item_detail["LockedFields"] = ["SortName"] 104 | 105 | JellyfinUtil.post_item(self.domain, self.key, item.get("Id"), item_detail) 106 | self.process_count += 1 107 | else: 108 | self.log.info(f"跳过,未知类型:{json.dumps(item)}") 109 | self.skip_count += 1 110 | 111 | def render_folder(self, view_id, collection_type): 112 | if collection_type is not None and collection_type.lower() == "music": 113 | # 专辑 114 | music_items = JellyfinUtil.get_music_items(self.domain, self.key, self.user_id, view_id) 115 | if music_items: 116 | self.render_items(music_items.get("Items", [])) 117 | 118 | # 艺术家 119 | artists = JellyfinUtil.get_artists(self.domain, self.key, self.user_id, view_id) 120 | if artists: 121 | self.render_items(artists.get("Items", [])) 122 | else: 123 | nut_map = JellyfinUtil.get_items(self.domain, self.key, self.user_id, view_id) 124 | if nut_map: 125 | self.render_items(nut_map.get("Items", [])) 126 | 127 | def processed_view(self, view): 128 | self.init_count() 129 | start_time = time.time() 130 | self.log.info(f"开始处理 {view.get('Name')}") 131 | self.render_folder(view.get("Id"), view.get("CollectionType")) 132 | elapsed_time = time.time() - start_time 133 | self.log.info(f"已跳过:{self.skip_count},已处理:{self.process_count}, 耗时 {elapsed_time:.2f} 秒") 134 | 135 | def init_count(self): 136 | self.process_count = 0 137 | self.skip_count = 0 138 | 139 | 140 | if __name__ == "__main__": 141 | logging.basicConfig(level=logging.INFO) 142 | handler = JellyfinHandler() 143 | handler.init() 144 | -------------------------------------------------------------------------------- /src/JellyfinUtil.py: -------------------------------------------------------------------------------- 1 | import requests 2 | import json 3 | import logging 4 | 5 | class JellyfinUtil: 6 | timeout = 3000 7 | log = logging.getLogger(__name__) 8 | 9 | @staticmethod 10 | def get_users(domain, key): 11 | try: 12 | url = f"{domain}/Users?api_key={key}" 13 | headers = {"Content-Type": "application/json"} 14 | response = requests.get(url, headers=headers, timeout=JellyfinUtil.timeout / 1000) 15 | if response.status_code == 200: 16 | return {"Users": response.json()} 17 | JellyfinUtil.log.error(f"获取用户列表API,服务器错误: {response.status_code}") 18 | return None 19 | except Exception as e: 20 | JellyfinUtil.log.error(f"请检查服务是否启动 {domain}") 21 | return None 22 | 23 | @staticmethod 24 | def get_views(domain, key, user_id): 25 | try: 26 | url = f"{domain}/Users/{user_id}/Views?api_key={key}" 27 | headers = {"Content-Type": "application/json"} 28 | response = requests.get(url, headers=headers, timeout=JellyfinUtil.timeout / 1000) 29 | if response.status_code == 200: 30 | return response.json() 31 | JellyfinUtil.log.error(f"获取媒体库API,服务器错误: {response.status_code}") 32 | return None 33 | except Exception as e: 34 | JellyfinUtil.log.error(f"请检查服务是否启动 {domain}") 35 | return None 36 | 37 | @staticmethod 38 | def get_items(domain, key, user_id, pid): 39 | try: 40 | url = f"{domain}/Users/{user_id}/Items?api_key={key}&ParentId={pid}" 41 | headers = {"Content-Type": "application/json"} 42 | response = requests.get(url, headers=headers, timeout=JellyfinUtil.timeout / 1000) 43 | if response.status_code == 200: 44 | return response.json() 45 | JellyfinUtil.log.error(f"获取对象列表API,服务器错误: {response.status_code}") 46 | return None 47 | except Exception as e: 48 | JellyfinUtil.log.error(f"请检查服务是否启动 {domain}") 49 | return None 50 | 51 | @staticmethod 52 | def get_music_items(domain, key, user_id, pid): 53 | try: 54 | url = f"{domain}/Users/{user_id}/Items?api_key={key}&IncludeItemTypes=MusicAlbum&Recursive=true&ParentId={pid}" 55 | headers = {"Content-Type": "application/json"} 56 | response = requests.get(url, headers=headers, timeout=JellyfinUtil.timeout / 1000) 57 | if response.status_code == 200: 58 | return response.json() 59 | JellyfinUtil.log.error(f"获取音乐对象,服务器错误: {response.status_code}") 60 | return None 61 | except Exception as e: 62 | JellyfinUtil.log.error(f"请检查服务是否启动 {domain}") 63 | return None 64 | 65 | @staticmethod 66 | def get_artists(domain, key, user_id, pid): 67 | try: 68 | url = f"{domain}/Artists?api_key={key}&userId={user_id}&ArtistType=Artist,AlbumArtist&Recursive=true&ParentId={pid}" 69 | headers = {"Content-Type": "application/json"} 70 | response = requests.get(url, headers=headers, timeout=JellyfinUtil.timeout / 1000) 71 | if response.status_code == 200: 72 | return response.json() 73 | JellyfinUtil.log.error(f"获取艺术家API,服务器错误: {response.status_code}") 74 | return None 75 | except Exception as e: 76 | JellyfinUtil.log.error(f"请检查服务是否启动 {domain}") 77 | return None 78 | 79 | @staticmethod 80 | def get_item(domain, key, user_id, item_id): 81 | try: 82 | url = f"{domain}/Users/{user_id}/Items/{item_id}?source=jellyfin_pinyin&api_key={key}" 83 | headers = {"Content-Type": "application/json"} 84 | response = requests.get(url, headers=headers, timeout=JellyfinUtil.timeout / 1000) 85 | if response.status_code == 200: 86 | return response.json() 87 | JellyfinUtil.log.error(f"获取对象API,服务器错误: {response.status_code}") 88 | return None 89 | except Exception as e: 90 | JellyfinUtil.log.error(f"请检查服务是否启动 {domain}") 91 | return None 92 | 93 | @staticmethod 94 | def post_item(domain, key, item_id, item): 95 | try: 96 | url = f"{domain}/Items/{item_id}?api_key={key}" 97 | headers = {"Content-Type": "application/json"} 98 | response = requests.post(url, headers=headers, data=json.dumps(item), timeout=JellyfinUtil.timeout / 1000) 99 | if response.status_code == 204: 100 | pass # 成功,无返回内容 101 | else: 102 | JellyfinUtil.log.error(f"更新对象API,服务器错误: {response.status_code}") 103 | except Exception as e: 104 | JellyfinUtil.log.error(f"请检查服务是否启动 {domain}") 105 | 106 | 107 | -------------------------------------------------------------------------------- /src/PinyinUtil.py: -------------------------------------------------------------------------------- 1 | from pypinyin import pinyin, Style 2 | 3 | class PinyinUtil: 4 | @staticmethod 5 | def get_pingyin(name): 6 | """ 7 | 将汉字转换为全拼 8 | """ 9 | pinyin_list = pinyin(name, style=Style.NORMAL) 10 | pinyin_str = ''.join([item[0] for item in pinyin_list]) 11 | return pinyin_str 12 | 13 | @staticmethod 14 | def get_pinyin_head_char(name): 15 | """ 16 | 返回中文的首字母 17 | """ 18 | pinyin_list = pinyin(name, style=Style.FIRST_LETTER) 19 | head_chars = ''.join([item[0] for item in pinyin_list]) 20 | return head_chars 21 | 22 | @staticmethod 23 | def get_cn_ascii(name): 24 | """ 25 | 将字符串转移为ASCII码 26 | """ 27 | return ''.join([hex(ord(char)).replace('0x', '') for char in name]) 28 | --------------------------------------------------------------------------------