react-native-consumet 1.0.0-rc.0 → 1.0.0-rc.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (245) hide show
  1. package/android/generated/java/com/consumet/NativeConsumetSpec.java +4 -0
  2. package/android/generated/jni/RNConsumetSpec-generated.cpp +6 -0
  3. package/android/generated/jni/react/renderer/components/RNConsumetSpec/RNConsumetSpecJSI-generated.cpp +8 -0
  4. package/android/generated/jni/react/renderer/components/RNConsumetSpec/RNConsumetSpecJSI.h +9 -0
  5. package/android/src/main/java/com/consumet/ConsumetModule.kt +7 -0
  6. package/android/src/main/java/com/consumet/DdosGuardModule.kt +248 -189
  7. package/ios/generated/RNConsumetSpec/RNConsumetSpec-generated.mm +7 -0
  8. package/ios/generated/RNConsumetSpec/RNConsumetSpec.h +2 -0
  9. package/ios/generated/RNConsumetSpecJSI-generated.cpp +8 -0
  10. package/ios/generated/RNConsumetSpecJSI.h +9 -0
  11. package/lib/commonjs/NativeConsumet.ts +28 -26
  12. package/lib/commonjs/extension-registry.json +13 -13
  13. package/lib/commonjs/extractors/filemoon.js +2 -2
  14. package/lib/commonjs/extractors/kwik.js +60 -15
  15. package/lib/commonjs/extractors/kwik.js.map +1 -1
  16. package/lib/commonjs/extractors/megacloud.js +6 -6
  17. package/lib/commonjs/index.js +2 -11
  18. package/lib/commonjs/index.js.map +1 -1
  19. package/lib/commonjs/models/types.js +4 -4
  20. package/lib/commonjs/models/video-extractor.js +4 -4
  21. package/lib/commonjs/providers/anime/animedrive.js +12 -12
  22. package/lib/commonjs/providers/anime/animekai.js +41 -41
  23. package/lib/commonjs/providers/anime/animepahe/animepahe.js +16 -15
  24. package/lib/commonjs/providers/anime/animepahe/animepahe.js.map +1 -1
  25. package/lib/commonjs/providers/anime/animepahe/create-animepahe.js +12 -9
  26. package/lib/commonjs/providers/anime/animepahe/create-animepahe.js.map +1 -1
  27. package/lib/commonjs/providers/anime/animesuge/animesuge.js +78 -0
  28. package/lib/commonjs/providers/anime/animesuge/animesuge.js.map +1 -0
  29. package/lib/commonjs/providers/anime/animesuge/create-animesuge.js +312 -0
  30. package/lib/commonjs/providers/anime/animesuge/create-animesuge.js.map +1 -0
  31. package/lib/commonjs/providers/anime/animeunity.js +13 -13
  32. package/lib/commonjs/providers/anime/index.js +4 -4
  33. package/lib/commonjs/providers/anime/index.js.map +1 -1
  34. package/lib/commonjs/providers/anime/marin.js +12 -12
  35. package/lib/commonjs/providers/anime/zoro/create-zoro.js +2 -2
  36. package/lib/commonjs/providers/anime/zoro/create-zoro.js.map +1 -1
  37. package/lib/commonjs/providers/anime/zoro/zoro.js +76 -74
  38. package/lib/commonjs/providers/anime/zoro/zoro.js.map +1 -1
  39. package/lib/commonjs/providers/manga/brmangas.js +3 -3
  40. package/lib/commonjs/providers/meta/anilist.js +91 -91
  41. package/lib/commonjs/providers/meta/mal.js +12 -12
  42. package/lib/commonjs/providers/meta/tmdb.js +21 -21
  43. package/lib/commonjs/providers/movies/himovies/create-himovies.js +16 -16
  44. package/lib/commonjs/providers/movies/himovies/himovies.js +16 -16
  45. package/lib/commonjs/providers/movies/multimovies.js +15 -15
  46. package/lib/commonjs/providers/movies/multistream/index.js +21 -20
  47. package/lib/commonjs/providers/movies/multistream/index.js.map +1 -1
  48. package/lib/commonjs/providers/movies/multistream/utils.js +142 -130
  49. package/lib/commonjs/providers/movies/multistream/utils.js.map +1 -1
  50. package/lib/commonjs/utils/ExtractorManager.js +15 -15
  51. package/lib/commonjs/utils/ExtractorManager.js.map +1 -1
  52. package/lib/commonjs/utils/ProviderManager.js +2 -1
  53. package/lib/commonjs/utils/ProviderManager.js.map +1 -1
  54. package/lib/commonjs/utils/create-extractor-context.js +9 -1
  55. package/lib/commonjs/utils/create-extractor-context.js.map +1 -1
  56. package/lib/commonjs/utils/create-provider-context.js +6 -2
  57. package/lib/commonjs/utils/create-provider-context.js.map +1 -1
  58. package/lib/commonjs/utils/extension-utils.js +44 -54
  59. package/lib/commonjs/utils/extension-utils.js.map +1 -1
  60. package/lib/commonjs/utils/index.js +2 -2
  61. package/lib/commonjs/utils/provider-maps.js +31 -0
  62. package/lib/commonjs/utils/provider-maps.js.map +1 -0
  63. package/lib/commonjs/utils/providers-list.js +4 -4
  64. package/lib/commonjs/utils/url-polyfill.js +4 -4
  65. package/lib/module/NativeConsumet.ts +28 -26
  66. package/lib/module/extension-registry.json +13 -13
  67. package/lib/module/extractors/filemoon.js +2 -2
  68. package/lib/module/extractors/kwik.js +60 -15
  69. package/lib/module/extractors/kwik.js.map +1 -1
  70. package/lib/module/extractors/megacloud.js +6 -6
  71. package/lib/module/index.js +3 -7
  72. package/lib/module/index.js.map +1 -1
  73. package/lib/module/models/types.js +4 -4
  74. package/lib/module/models/video-extractor.js +4 -4
  75. package/lib/module/providers/anime/animedrive.js +12 -12
  76. package/lib/module/providers/anime/animekai.js +41 -41
  77. package/lib/module/providers/anime/animepahe/animepahe.js +14 -14
  78. package/lib/module/providers/anime/animepahe/animepahe.js.map +1 -1
  79. package/lib/module/providers/anime/animepahe/create-animepahe.js +13 -9
  80. package/lib/module/providers/anime/animepahe/create-animepahe.js.map +1 -1
  81. package/lib/module/providers/anime/animesuge/animesuge.js +73 -0
  82. package/lib/module/providers/anime/animesuge/animesuge.js.map +1 -0
  83. package/lib/module/providers/anime/animesuge/create-animesuge.js +309 -0
  84. package/lib/module/providers/anime/animesuge/create-animesuge.js.map +1 -0
  85. package/lib/module/providers/anime/animeunity.js +13 -13
  86. package/lib/module/providers/anime/index.js +2 -2
  87. package/lib/module/providers/anime/index.js.map +1 -1
  88. package/lib/module/providers/anime/marin.js +12 -12
  89. package/lib/module/providers/anime/zoro/create-zoro.js +3 -2
  90. package/lib/module/providers/anime/zoro/create-zoro.js.map +1 -1
  91. package/lib/module/providers/anime/zoro/zoro.js +74 -73
  92. package/lib/module/providers/anime/zoro/zoro.js.map +1 -1
  93. package/lib/module/providers/manga/brmangas.js +3 -3
  94. package/lib/module/providers/meta/anilist.js +91 -91
  95. package/lib/module/providers/meta/mal.js +12 -12
  96. package/lib/module/providers/meta/tmdb.js +21 -21
  97. package/lib/module/providers/movies/himovies/create-himovies.js +16 -16
  98. package/lib/module/providers/movies/himovies/himovies.js +16 -16
  99. package/lib/module/providers/movies/multimovies.js +15 -15
  100. package/lib/module/providers/movies/multistream/index.js +21 -20
  101. package/lib/module/providers/movies/multistream/index.js.map +1 -1
  102. package/lib/module/providers/movies/multistream/utils.js +141 -129
  103. package/lib/module/providers/movies/multistream/utils.js.map +1 -1
  104. package/lib/module/utils/ExtractorManager.js +16 -16
  105. package/lib/module/utils/ExtractorManager.js.map +1 -1
  106. package/lib/module/utils/ProviderManager.js +2 -1
  107. package/lib/module/utils/ProviderManager.js.map +1 -1
  108. package/lib/module/utils/create-extractor-context.js +10 -1
  109. package/lib/module/utils/create-extractor-context.js.map +1 -1
  110. package/lib/module/utils/create-provider-context.js +8 -4
  111. package/lib/module/utils/create-provider-context.js.map +1 -1
  112. package/lib/module/utils/extension-utils.js +23 -33
  113. package/lib/module/utils/extension-utils.js.map +1 -1
  114. package/lib/module/utils/index.js +1 -1
  115. package/lib/module/utils/index.js.map +1 -1
  116. package/lib/module/utils/provider-maps.js +27 -0
  117. package/lib/module/utils/provider-maps.js.map +1 -0
  118. package/lib/module/utils/providers-list.js +4 -4
  119. package/lib/module/utils/url-polyfill.js +4 -4
  120. package/lib/typescript/commonjs/src/NativeConsumet.d.ts +2 -0
  121. package/lib/typescript/commonjs/src/NativeConsumet.d.ts.map +1 -1
  122. package/lib/typescript/commonjs/src/extractors/kwik.d.ts.map +1 -1
  123. package/lib/typescript/commonjs/src/index.d.ts +6 -6
  124. package/lib/typescript/commonjs/src/index.d.ts.map +1 -1
  125. package/lib/typescript/commonjs/src/models/extractor-context.d.ts +8 -0
  126. package/lib/typescript/commonjs/src/models/extractor-context.d.ts.map +1 -1
  127. package/lib/typescript/commonjs/src/models/index.d.ts +2 -2
  128. package/lib/typescript/commonjs/src/models/index.d.ts.map +1 -1
  129. package/lib/typescript/commonjs/src/models/provider-context.d.ts +6 -2
  130. package/lib/typescript/commonjs/src/models/provider-context.d.ts.map +1 -1
  131. package/lib/typescript/commonjs/src/providers/anime/animepahe/animepahe.d.ts.map +1 -1
  132. package/lib/typescript/commonjs/src/providers/anime/animepahe/create-animepahe.d.ts +1 -1
  133. package/lib/typescript/commonjs/src/providers/anime/animepahe/create-animepahe.d.ts.map +1 -1
  134. package/lib/typescript/commonjs/src/providers/anime/animesuge/animesuge.d.ts +34 -0
  135. package/lib/typescript/commonjs/src/providers/anime/animesuge/animesuge.d.ts.map +1 -0
  136. package/lib/typescript/commonjs/src/providers/anime/animesuge/create-animesuge.d.ts +14 -0
  137. package/lib/typescript/commonjs/src/providers/anime/animesuge/create-animesuge.d.ts.map +1 -0
  138. package/lib/typescript/commonjs/src/providers/anime/index.d.ts +2 -2
  139. package/lib/typescript/commonjs/src/providers/anime/index.d.ts.map +1 -1
  140. package/lib/typescript/commonjs/src/providers/anime/zoro/create-zoro.d.ts +1 -1
  141. package/lib/typescript/commonjs/src/providers/anime/zoro/create-zoro.d.ts.map +1 -1
  142. package/lib/typescript/commonjs/src/providers/anime/zoro/zoro.d.ts.map +1 -1
  143. package/lib/typescript/commonjs/src/providers/movies/multistream/index.d.ts +1 -1
  144. package/lib/typescript/commonjs/src/providers/movies/multistream/index.d.ts.map +1 -1
  145. package/lib/typescript/commonjs/src/providers/movies/multistream/utils.d.ts +2 -2
  146. package/lib/typescript/commonjs/src/providers/movies/multistream/utils.d.ts.map +1 -1
  147. package/lib/typescript/commonjs/src/utils/ProviderManager.d.ts +1 -1
  148. package/lib/typescript/commonjs/src/utils/ProviderManager.d.ts.map +1 -1
  149. package/lib/typescript/commonjs/src/utils/create-extractor-context.d.ts.map +1 -1
  150. package/lib/typescript/commonjs/src/utils/create-provider-context.d.ts.map +1 -1
  151. package/lib/typescript/commonjs/src/utils/extension-utils.d.ts +1 -20
  152. package/lib/typescript/commonjs/src/utils/extension-utils.d.ts.map +1 -1
  153. package/lib/typescript/commonjs/src/utils/index.d.ts +2 -1
  154. package/lib/typescript/commonjs/src/utils/index.d.ts.map +1 -1
  155. package/lib/typescript/commonjs/src/utils/provider-maps.d.ts +27 -0
  156. package/lib/typescript/commonjs/src/utils/provider-maps.d.ts.map +1 -0
  157. package/lib/typescript/module/src/NativeConsumet.d.ts +2 -0
  158. package/lib/typescript/module/src/NativeConsumet.d.ts.map +1 -1
  159. package/lib/typescript/module/src/extractors/kwik.d.ts.map +1 -1
  160. package/lib/typescript/module/src/index.d.ts +6 -6
  161. package/lib/typescript/module/src/index.d.ts.map +1 -1
  162. package/lib/typescript/module/src/models/extractor-context.d.ts +8 -0
  163. package/lib/typescript/module/src/models/extractor-context.d.ts.map +1 -1
  164. package/lib/typescript/module/src/models/index.d.ts +2 -2
  165. package/lib/typescript/module/src/models/index.d.ts.map +1 -1
  166. package/lib/typescript/module/src/models/provider-context.d.ts +6 -2
  167. package/lib/typescript/module/src/models/provider-context.d.ts.map +1 -1
  168. package/lib/typescript/module/src/providers/anime/animepahe/animepahe.d.ts.map +1 -1
  169. package/lib/typescript/module/src/providers/anime/animepahe/create-animepahe.d.ts +1 -1
  170. package/lib/typescript/module/src/providers/anime/animepahe/create-animepahe.d.ts.map +1 -1
  171. package/lib/typescript/module/src/providers/anime/animesuge/animesuge.d.ts +34 -0
  172. package/lib/typescript/module/src/providers/anime/animesuge/animesuge.d.ts.map +1 -0
  173. package/lib/typescript/module/src/providers/anime/animesuge/create-animesuge.d.ts +14 -0
  174. package/lib/typescript/module/src/providers/anime/animesuge/create-animesuge.d.ts.map +1 -0
  175. package/lib/typescript/module/src/providers/anime/index.d.ts +2 -2
  176. package/lib/typescript/module/src/providers/anime/index.d.ts.map +1 -1
  177. package/lib/typescript/module/src/providers/anime/zoro/create-zoro.d.ts +1 -1
  178. package/lib/typescript/module/src/providers/anime/zoro/create-zoro.d.ts.map +1 -1
  179. package/lib/typescript/module/src/providers/anime/zoro/zoro.d.ts.map +1 -1
  180. package/lib/typescript/module/src/providers/movies/multistream/index.d.ts +1 -1
  181. package/lib/typescript/module/src/providers/movies/multistream/index.d.ts.map +1 -1
  182. package/lib/typescript/module/src/providers/movies/multistream/utils.d.ts +2 -2
  183. package/lib/typescript/module/src/providers/movies/multistream/utils.d.ts.map +1 -1
  184. package/lib/typescript/module/src/utils/ProviderManager.d.ts +1 -1
  185. package/lib/typescript/module/src/utils/ProviderManager.d.ts.map +1 -1
  186. package/lib/typescript/module/src/utils/create-extractor-context.d.ts.map +1 -1
  187. package/lib/typescript/module/src/utils/create-provider-context.d.ts.map +1 -1
  188. package/lib/typescript/module/src/utils/extension-utils.d.ts +1 -20
  189. package/lib/typescript/module/src/utils/extension-utils.d.ts.map +1 -1
  190. package/lib/typescript/module/src/utils/index.d.ts +2 -1
  191. package/lib/typescript/module/src/utils/index.d.ts.map +1 -1
  192. package/lib/typescript/module/src/utils/provider-maps.d.ts +27 -0
  193. package/lib/typescript/module/src/utils/provider-maps.d.ts.map +1 -0
  194. package/package.json +6 -2
  195. package/src/NativeConsumet.ts +2 -0
  196. package/src/extension-registry.json +81 -81
  197. package/src/extractors/StreamP2P.ts +60 -60
  198. package/src/extractors/filemoon.ts +58 -58
  199. package/src/extractors/index.ts +41 -41
  200. package/src/extractors/kwik.ts +113 -50
  201. package/src/extractors/megacloud.ts +163 -163
  202. package/src/extractors/mixdrop.ts +31 -31
  203. package/src/extractors/mp4upload.ts +31 -31
  204. package/src/extractors/streamhub.ts +58 -58
  205. package/src/extractors/streamwish.ts +120 -120
  206. package/src/extractors/vidhide.ts +59 -59
  207. package/src/index.tsx +176 -175
  208. package/src/models/extension-manifest.ts +77 -77
  209. package/src/models/extractor-context.ts +55 -41
  210. package/src/models/index.ts +107 -106
  211. package/src/models/provider-context.ts +192 -182
  212. package/src/models/types.ts +531 -531
  213. package/src/models/video-extractor.ts +48 -48
  214. package/src/providers/anime/animedrive.ts +245 -245
  215. package/src/providers/anime/animekai.ts +627 -627
  216. package/src/providers/anime/animepahe/animepahe.ts +76 -76
  217. package/src/providers/anime/animepahe/create-animepahe.ts +350 -348
  218. package/src/providers/anime/animesuge/animesuge.ts +77 -0
  219. package/src/providers/anime/animesuge/create-animesuge.ts +327 -0
  220. package/src/providers/anime/animeunity.ts +216 -216
  221. package/src/providers/anime/index.ts +21 -21
  222. package/src/providers/anime/marin.ts +319 -319
  223. package/src/providers/anime/zoro/create-zoro.ts +656 -655
  224. package/src/providers/anime/zoro/zoro.ts +198 -197
  225. package/src/providers/index.ts +7 -7
  226. package/src/providers/manga/brmangas.ts +144 -144
  227. package/src/providers/meta/anilist.ts +2108 -2108
  228. package/src/providers/meta/mal.ts +635 -635
  229. package/src/providers/meta/tmdb.ts +470 -470
  230. package/src/providers/movies/himovies/create-himovies.ts +529 -529
  231. package/src/providers/movies/himovies/himovies.ts +90 -90
  232. package/src/providers/movies/index.ts +15 -15
  233. package/src/providers/movies/multimovies.ts +495 -495
  234. package/src/providers/movies/multistream/index.ts +232 -231
  235. package/src/providers/movies/multistream/utils.ts +147 -270
  236. package/src/utils/ExtractorManager.ts +311 -311
  237. package/src/utils/ProviderManager.ts +423 -424
  238. package/src/utils/create-extractor-context.ts +36 -22
  239. package/src/utils/create-provider-context.ts +117 -107
  240. package/src/utils/extension-utils.ts +105 -114
  241. package/src/utils/index.ts +96 -95
  242. package/src/utils/provider-maps.ts +31 -0
  243. package/src/utils/providers-list.ts +27 -27
  244. package/src/utils/url-polyfill.ts +642 -642
  245. package/src/utils/utils.ts +374 -374
@@ -1,635 +1,635 @@
1
- import axios from 'axios';
2
- import { load } from 'cheerio';
3
-
4
- import {
5
- AnimeParser,
6
- type ISearch,
7
- type IAnimeInfo,
8
- MediaStatus,
9
- type IAnimeResult,
10
- type ISource,
11
- type IAnimeEpisode,
12
- SubOrDub,
13
- type IEpisodeServer,
14
- MediaFormat,
15
- } from '../../models';
16
- import { substringAfter, substringBefore, calculateStringSimilarity, kitsuSearchQuery, range } from '../../utils';
17
- import Zoro from '../anime/zoro/zoro';
18
- import Anify from '../anime/anify';
19
- import { ANIFY_URL } from '../../utils/utils';
20
-
21
- class Myanimelist extends AnimeParser {
22
- override readonly name = 'Myanimelist';
23
- protected override baseUrl = 'https://myanimelist.net/';
24
- protected override logo = 'https://en.wikipedia.org/wiki/MyAnimeList#/media/File:MyAnimeList.png';
25
- protected override classPath = 'META.Myanimelist';
26
-
27
- private readonly anilistGraphqlUrl = 'https://graphql.anilist.co';
28
- private readonly kitsuGraphqlUrl = 'https://kitsu.app/api/graphql';
29
- private readonly malSyncUrl = 'https://api.malsync.moe';
30
- private readonly anifyUrl = ANIFY_URL;
31
- provider: AnimeParser;
32
-
33
- /**
34
- * This class maps myanimelist to kitsu with any other anime provider.
35
- * kitsu is used for episode images, titles and description.
36
- * @param provider anime provider (optional) default: Gogoanime
37
- */
38
- constructor(provider?: AnimeParser) {
39
- super();
40
- this.provider = provider || new Zoro();
41
- }
42
-
43
- private malStatusToMediaStatus(status: string): MediaStatus {
44
- if (status === 'currently airing') return MediaStatus.ONGOING;
45
- else if (status === 'finished airing') return MediaStatus.COMPLETED;
46
- else if (status === 'not yet aired') return MediaStatus.NOT_YET_AIRED;
47
- return MediaStatus.UNKNOWN;
48
- }
49
-
50
- private async populateEpisodeList(episodes: IAnimeEpisode[], url: string, count: number = 1): Promise<void> {
51
- try {
52
- const { data } = await axios.request({
53
- method: 'get',
54
- url: `${url}?p=${count}`,
55
- headers: {
56
- 'user-agent':
57
- 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36 Edg/107.0.1418.35',
58
- },
59
- });
60
-
61
- let hasEpisodes = false;
62
- const $ = load(data);
63
- for (const elem of $('.video-list').toArray()) {
64
- const href = $(elem).attr('href');
65
- const image = $(elem).find('img').attr('data-src');
66
- const titleDOM = $(elem).find('.episode-title');
67
- const title = titleDOM?.text();
68
- titleDOM.remove();
69
-
70
- const numberDOM = $(elem).find('.title').text().split(' ');
71
- let number = 0;
72
- if (numberDOM.length > 1) {
73
- number = Number(numberDOM[1]);
74
- }
75
- if (href && href.indexOf('myanimelist.net/anime') > -1) {
76
- hasEpisodes = true;
77
- episodes.push({
78
- id: '',
79
- number,
80
- title,
81
- image,
82
- });
83
- }
84
- }
85
-
86
- if (hasEpisodes) await this.populateEpisodeList(episodes, url, ++count);
87
- } catch (err) {
88
- console.error(err);
89
- }
90
- }
91
-
92
- override search = async (query: string, page: number = 1): Promise<ISearch<IAnimeResult>> => {
93
- const searchResults: ISearch<IAnimeResult> = {
94
- currentPage: page,
95
- results: [],
96
- };
97
-
98
- const { data } = await axios.request({
99
- method: 'get',
100
- url: `https://myanimelist.net/anime.php?q=${query}&cat=anime&show=${50 * (page - 1)}`,
101
- headers: {
102
- 'user-agent':
103
- 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36 Edg/107.0.1418.35',
104
- },
105
- });
106
-
107
- const $ = load(data);
108
-
109
- const pages = $('.normal_header').find('span').children();
110
- const maxPage = parseInt(pages.last().text());
111
- const hasNextPage = page < maxPage;
112
- searchResults.hasNextPage = hasNextPage;
113
-
114
- $('tr').each((i, item) => {
115
- const id = $(item).find('.hoverinfo_trigger').attr('href')?.split('anime/')[1]!.split('/')[0];
116
- const title = $(item).find('strong').text();
117
- const description = $(item).find('.pt4').text().replace('...read more.', '...');
118
- const type = $(item).children().eq(2).text().trim();
119
- const episodeCount = $(item).children().eq(3).text().trim();
120
- const score = (parseFloat($(item).children().eq(4).text()) * 10).toFixed(0);
121
- const imageTmp = $(item).children().first().find('img').attr('data-src');
122
- const imageUrl = `https://cdn.myanimelist.net/images/anime/${imageTmp?.split('anime/')[1]}`;
123
-
124
- if (title !== '') {
125
- searchResults.results.push({
126
- id: id ?? '',
127
- title: title,
128
- image: imageUrl,
129
- rating: parseInt(score),
130
- description: description,
131
- totalEpisodes: parseInt(episodeCount),
132
- type:
133
- type === 'TV'
134
- ? MediaFormat.TV
135
- : type === 'TV_SHORT'
136
- ? MediaFormat.TV_SHORT
137
- : type === 'MOVIE'
138
- ? MediaFormat.MOVIE
139
- : type === 'SPECIAL'
140
- ? MediaFormat.SPECIAL
141
- : type === 'OVA'
142
- ? MediaFormat.OVA
143
- : type === 'ONA'
144
- ? MediaFormat.ONA
145
- : type === 'MUSIC'
146
- ? MediaFormat.MUSIC
147
- : type === 'MANGA'
148
- ? MediaFormat.MANGA
149
- : type === 'NOVEL'
150
- ? MediaFormat.NOVEL
151
- : type === 'ONE_SHOT'
152
- ? MediaFormat.ONE_SHOT
153
- : undefined,
154
- });
155
- }
156
- });
157
-
158
- return searchResults;
159
- };
160
-
161
- /**
162
- *
163
- * @param animeId anime id
164
- * @param fetchFiller fetch filler episodes
165
- */
166
- fetchAnimeInfo = async (animeId: string, dub: boolean = false, fetchFiller: boolean = false): Promise<IAnimeInfo> => {
167
- try {
168
- const animeInfo = await this.fetchMalInfoById(animeId);
169
-
170
- const titleWithLanguages = animeInfo?.title as {
171
- english: string;
172
- romaji: string;
173
- native: string;
174
- userPreferred: string;
175
- };
176
- let fillerEpisodes: { 'number': string; 'filler-bool': boolean }[];
177
- if (
178
- this.provider instanceof Zoro &&
179
- !dub &&
180
- (animeInfo.status === MediaStatus.ONGOING ||
181
- range({ from: 2000, to: new Date().getFullYear() + 1 }).includes(animeInfo.startDate?.year!))
182
- ) {
183
- try {
184
- animeInfo.episodes = (
185
- await new Anify(
186
- undefined,
187
- undefined,
188
- this.provider.name.toLowerCase() as 'gogoanime' | 'zoro' | '9anime' | 'animepahe'
189
- ).fetchAnimeInfo(animeId)
190
- ).episodes?.map((item: any) => ({
191
- id: item.slug,
192
- title: item.title,
193
- description: item.description,
194
- number: item.number,
195
- image: item.image,
196
- }));
197
- animeInfo.episodes?.reverse();
198
- } catch (err) {
199
- animeInfo.episodes = await this.findAnimeSlug(
200
- titleWithLanguages?.english ||
201
- titleWithLanguages?.romaji ||
202
- titleWithLanguages?.native ||
203
- titleWithLanguages?.userPreferred,
204
- animeInfo.season!,
205
- animeInfo.startDate?.year!,
206
- animeId,
207
- dub
208
- );
209
-
210
- animeInfo.episodes = animeInfo.episodes?.map((episode: IAnimeEpisode) => {
211
- if (!episode.image) episode.image = animeInfo.image;
212
-
213
- return episode;
214
- });
215
-
216
- return animeInfo;
217
- }
218
- } else
219
- animeInfo.episodes = await this.findAnimeSlug(
220
- titleWithLanguages?.english ||
221
- titleWithLanguages?.romaji ||
222
- titleWithLanguages?.native ||
223
- titleWithLanguages?.userPreferred,
224
- animeInfo.season!,
225
- animeInfo.startDate?.year!,
226
- animeId,
227
- dub
228
- );
229
-
230
- if (fetchFiller) {
231
- const { data: fillerData } = await axios({
232
- baseURL: `https://raw.githubusercontent.com/saikou-app/mal-id-filler-list/main/fillers/${animeId}.json`,
233
- method: 'GET',
234
- validateStatus: () => true,
235
- });
236
-
237
- if (!fillerData.toString().startsWith('404')) {
238
- fillerEpisodes = [];
239
- fillerEpisodes?.push(
240
- ...(fillerData.episodes as {
241
- 'number': string;
242
- 'filler-bool': boolean;
243
- }[])
244
- );
245
- }
246
- }
247
-
248
- animeInfo.episodes = animeInfo.episodes?.map((episode: IAnimeEpisode) => {
249
- if (!episode.image) episode.image = animeInfo.image;
250
-
251
- if (fetchFiller && fillerEpisodes?.length > 0 && fillerEpisodes?.length >= animeInfo.episodes!.length) {
252
- if (fillerEpisodes[episode.number! - 1])
253
- episode.isFiller = new Boolean(fillerEpisodes?.[episode.number! - 1]!['filler-bool']).valueOf();
254
- }
255
-
256
- return episode;
257
- });
258
-
259
- return animeInfo;
260
- } catch (err) {
261
- console.error(err);
262
- throw err;
263
- }
264
- };
265
-
266
- override fetchEpisodeSources = async (episodeId: string, ...args: any): Promise<ISource> => {
267
- try {
268
- if (episodeId.includes('/') && this.provider instanceof Anify)
269
- return new Anify().fetchEpisodeSources(episodeId, args[0], args[1]);
270
- return this.provider.fetchEpisodeSources(episodeId, ...args);
271
- } catch (err) {
272
- throw new Error(`Failed to fetch episode sources from ${this.provider.name}: ${err}`);
273
- }
274
- };
275
-
276
- fetchEpisodeServers(episodeId: string): Promise<IEpisodeServer[]> {
277
- return this.provider.fetchEpisodeServers(episodeId);
278
- }
279
-
280
- private findAnimeRaw = async (slug: string, externalLinks?: any) => {
281
- const findAnime = (await this.provider.search(slug)) as ISearch<IAnimeResult>;
282
- if (findAnime.results.length === 0) return [];
283
-
284
- // Sort the retrieved info for more accurate results.
285
-
286
- findAnime.results.sort((a, b) => {
287
- const targetTitle = slug.toLowerCase();
288
-
289
- let firstTitle: string;
290
- let secondTitle: string;
291
-
292
- if (typeof a.title === 'string') firstTitle = a.title as string;
293
- else firstTitle = a.title.english ?? a.title.romaji ?? '';
294
-
295
- if (typeof b.title === 'string') secondTitle = b.title as string;
296
- else secondTitle = b.title.english ?? b.title.romaji ?? '';
297
-
298
- const firstRating = calculateStringSimilarity(targetTitle, firstTitle.toLowerCase());
299
- const secondRating = calculateStringSimilarity(targetTitle, secondTitle.toLowerCase());
300
-
301
- // Sort in descending order
302
- return secondRating - firstRating;
303
- });
304
-
305
- // TODO: use much better way than this
306
- return (await this.provider.fetchAnimeInfo(findAnime.results[0]!.id)) as IAnimeInfo;
307
- };
308
-
309
- private findAnimeSlug = async (
310
- title: string,
311
- season: string,
312
- startDate: number,
313
- malId: string,
314
- dub: boolean,
315
- externalLinks?: any
316
- ): Promise<IAnimeEpisode[]> => {
317
- if (this.provider instanceof Anify) return (await this.provider.fetchAnimeInfo(malId)).episodes!;
318
-
319
- // console.log({ title });
320
- const slug = title?.replace(/[^0-9a-zA-Z]+/g, ' ');
321
-
322
- let possibleAnime: any | undefined;
323
-
324
- possibleAnime = await this.findAnimeRaw(slug, externalLinks);
325
-
326
- // To avoid a new request, lets match and see if the anime show found is in sub/dub
327
-
328
- const expectedType = dub ? SubOrDub.DUB : SubOrDub.SUB;
329
-
330
- if (possibleAnime.subOrDub !== SubOrDub.BOTH && possibleAnime.subOrDub !== expectedType) {
331
- return [];
332
- }
333
-
334
- if (this.provider instanceof Zoro) {
335
- // Set the correct episode sub/dub request type
336
- possibleAnime.episodes.forEach((_: any, index: number) => {
337
- if (possibleAnime.subOrDub === SubOrDub.BOTH) {
338
- possibleAnime.episodes[index].id = possibleAnime.episodes[index].id.replace(`$both`, dub ? '$dub' : '$sub');
339
- }
340
- });
341
- }
342
-
343
- const possibleProviderEpisodes = possibleAnime.episodes as IAnimeEpisode[];
344
-
345
- if (
346
- typeof possibleProviderEpisodes[0]?.image !== 'undefined' &&
347
- typeof possibleProviderEpisodes[0]?.title !== 'undefined' &&
348
- typeof possibleProviderEpisodes[0]?.description !== 'undefined'
349
- )
350
- return possibleProviderEpisodes;
351
-
352
- const options = {
353
- headers: { 'Content-Type': 'application/json' },
354
- query: kitsuSearchQuery(slug),
355
- };
356
-
357
- const newEpisodeList = await this.findKitsuAnime(possibleProviderEpisodes, options, season, startDate);
358
-
359
- return newEpisodeList;
360
- };
361
-
362
- private findKitsuAnime = async (
363
- possibleProviderEpisodes: IAnimeEpisode[],
364
- options: {},
365
- season?: string,
366
- startDate?: number
367
- ) => {
368
- const kitsuEpisodes = await axios.post(this.kitsuGraphqlUrl, options);
369
- const episodesList = new Map();
370
- if (kitsuEpisodes?.data.data) {
371
- const { nodes } = kitsuEpisodes.data.data.searchAnimeByTitle;
372
-
373
- if (nodes) {
374
- nodes.forEach((node: any) => {
375
- if (node.season === season && node.startDate.trim().split('-')[0] === startDate?.toString()) {
376
- const episodes = node.episodes.nodes;
377
-
378
- for (const episode of episodes) {
379
- const i = episode?.number.toString().replace(/"/g, '');
380
- let name;
381
- let description;
382
- let thumbnail;
383
-
384
- if (episode?.description?.en)
385
- description = episode?.description.en.toString().replace(/"/g, '').replace('\\n', '\n');
386
- if (episode?.thumbnail) thumbnail = episode?.thumbnail.original.url.toString().replace(/"/g, '');
387
-
388
- if (episode) {
389
- if (episode.titles?.canonical) name = episode.titles.canonical.toString().replace(/"/g, '');
390
- episodesList.set(i, {
391
- episodeNum: episode?.number.toString().replace(/"/g, ''),
392
- title: name,
393
- description,
394
- thumbnail,
395
- });
396
- continue;
397
- }
398
- episodesList.set(i, {
399
- episodeNum: undefined,
400
- title: undefined,
401
- description: undefined,
402
- thumbnail,
403
- });
404
- }
405
- }
406
- });
407
- }
408
- }
409
-
410
- const newEpisodeList: IAnimeEpisode[] = [];
411
- if (possibleProviderEpisodes?.length !== 0) {
412
- possibleProviderEpisodes?.forEach((ep: any, i: any) => {
413
- const j = (i + 1).toString();
414
- newEpisodeList.push({
415
- id: ep.id as string,
416
- title: ep.title ?? episodesList.get(j)?.title ?? null,
417
- image: ep.image ?? episodesList.get(j)?.thumbnail ?? null,
418
- number: ep.number as number,
419
- description: ep.description ?? episodesList.get(j)?.description ?? null,
420
- url: (ep.url as string) ?? null,
421
- });
422
- });
423
- }
424
-
425
- return newEpisodeList;
426
- };
427
-
428
- /**
429
- *
430
- * @param id anime id
431
- * @returns anime info without streamable episodes
432
- */
433
- fetchMalInfoById = async (id: string): Promise<IAnimeInfo> => {
434
- const animeInfo: IAnimeInfo = {
435
- id: id,
436
- title: '',
437
- };
438
-
439
- const { data } = await axios.request({
440
- method: 'GET',
441
- url: `https://myanimelist.net/anime/${id}`,
442
- headers: {
443
- 'user-agent':
444
- 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36 Edg/107.0.1418.35',
445
- },
446
- });
447
-
448
- const $ = load(data);
449
- const episodes: IAnimeEpisode[] = [];
450
- const desc = $('[itemprop="description"]').first().text();
451
- const imageElem = $('[itemprop="image"]').first();
452
- const image = imageElem.attr('src') || imageElem.attr('data-image') || imageElem.attr('data-src');
453
- const genres: string[] = [];
454
- const genreDOM = $('[itemprop="genre"]').get();
455
-
456
- genreDOM.forEach((elem) => genres.push($(elem).text()));
457
-
458
- animeInfo.genres = genres;
459
- animeInfo.image = image;
460
- animeInfo.description = desc;
461
- animeInfo.title = {
462
- english: $('.js-alternative-titles.hide').children().eq(0).text().replace('English: ', '').trim(),
463
- romaji: $('.title-name').text(),
464
- native: $('.js-alternative-titles.hide').parent().children().eq(9).text().trim(),
465
- userPreferred: $('.js-alternative-titles.hide').children().eq(0).text().replace('English: ', '').trim(),
466
- };
467
-
468
- animeInfo.synonyms = $('.js-alternative-titles.hide')
469
- .parent()
470
- .children()
471
- .eq(8)
472
- .text()
473
- .replace('Synonyms:', '')
474
- .trim()
475
- .split(',');
476
- animeInfo.studios = [];
477
- animeInfo.popularity = parseInt($('.numbers.popularity').text().trim().replace('Popularity #', '').trim());
478
-
479
- const producers: string[] = [];
480
- $('a').each(function (i: number, link: any) {
481
- if ($(link).attr('href')?.includes('producer') && $(link).parent().children().eq(0).text() === 'Producers:') {
482
- producers.push($(link).text());
483
- }
484
- });
485
- animeInfo.producers = producers;
486
- // animeInfo.episodes = episodes;
487
-
488
- const teaserDOM = $('.video-promotion > a');
489
- if (teaserDOM.length > 0) {
490
- const teaserURL = $(teaserDOM).attr('href');
491
- const style = $(teaserDOM).attr('style');
492
- if (teaserURL) {
493
- animeInfo.trailer = {
494
- id: substringAfter(teaserURL, 'embed/').split('?')[0]!,
495
- site: 'https://youtube.com/watch?v=',
496
- thumbnail: style ? substringBefore(substringAfter(style, "url('"), "'") : '',
497
- };
498
- }
499
- }
500
- const ops = $('.theme-songs.js-theme-songs.opnening').find('tr').get();
501
-
502
- const ignoreList = ['Apple Music', 'Youtube Music', 'Amazon Music', 'Spotify'];
503
- animeInfo.openings = ops.map((element: any) => {
504
- //console.log($(element).text().trim());
505
- const name = $(element).children().eq(1).children().first().text().trim();
506
- if (!ignoreList.includes(name)) {
507
- if ($(element).find('.theme-song-index').length !== 0) {
508
- const index = $(element).find('.theme-song-index').text().trim();
509
- const band = $(element).find('.theme-song-artist').text().trim();
510
- const episodes = $(element).find('.theme-song-episode').text().trim();
511
- //console.log($(element).children().eq(1).text().trim().split(index)[1]);
512
-
513
- return {
514
- name: $(element).children().eq(1).text().trim().split(index)[1]?.split(band)[0]?.trim(),
515
- band: band.replace('by ', ''),
516
- episodes: episodes,
517
- };
518
- } else {
519
- const band = $(element).find('.theme-song-artist').text().trim();
520
- const episodes = $(element).find('.theme-song-episode').text().trim();
521
- return {
522
- name: $(element).children().eq(1).text().trim()?.split(band)[0]?.trim(),
523
- band: band.replace('by ', ''),
524
- episodes: episodes,
525
- };
526
- }
527
- }
528
- });
529
- animeInfo.openings = (animeInfo.openings as any[]).filter(function (element: any) {
530
- return element !== undefined;
531
- });
532
-
533
- const eds = $('.theme-songs.js-theme-songs.ending').find('tr').get();
534
- animeInfo.endings = eds.map((element: any) => {
535
- //console.log($(element).text().trim());
536
- const name = $(element).children().eq(1).children().first().text().trim();
537
- if (!ignoreList.includes(name)) {
538
- if ($(element).find('.theme-song-index').length !== 0) {
539
- const index = $(element).find('.theme-song-index').text().trim();
540
- const band = $(element).find('.theme-song-artist').text().trim();
541
- const episodes = $(element).find('.theme-song-episode').text().trim();
542
- //console.log($(element).children().eq(1).text().trim().split(index)[1]);
543
-
544
- return {
545
- name: $(element).children().eq(1).text().trim().split(index)[1]?.split(band)[0]?.trim(),
546
- band: band.replace('by ', ''),
547
- episodes: episodes,
548
- };
549
- } else {
550
- const band = $(element).find('.theme-song-artist').text().trim();
551
- const episodes = $(element).find('.theme-song-episode').text().trim();
552
- return {
553
- name: $(element).children().eq(1).text().trim()?.split(band)[0]?.trim(),
554
- band: band.replace('by ', ''),
555
- episodes: episodes,
556
- };
557
- }
558
- }
559
- });
560
- animeInfo.endings = (animeInfo.endings as any[]).filter(function (element: any) {
561
- return element !== undefined;
562
- });
563
-
564
- const description = $('.spaceit_pad').get();
565
-
566
- description.forEach((elem: any) => {
567
- const text = $(elem).text().toLowerCase().trim();
568
- const key = text.split(':')[0];
569
- const value = substringAfter(text, `${key}:`).trim();
570
- switch (key) {
571
- case 'status':
572
- animeInfo.status = this.malStatusToMediaStatus(value);
573
- break;
574
- case 'episodes':
575
- animeInfo.totalEpisodes = parseInt(value);
576
- if (isNaN(animeInfo.totalEpisodes)) animeInfo.totalEpisodes = 0;
577
- break;
578
- case 'premiered':
579
- animeInfo.season = value.split(' ')[0]?.toUpperCase();
580
- break;
581
- case 'aired':
582
- const dates = value.split('to');
583
- if (dates.length >= 2) {
584
- const start = dates[0]?.trim();
585
- const end = dates[1]?.trim();
586
- const startDate = new Date(start!);
587
- const endDate = new Date(end!);
588
-
589
- if (startDate.toString() !== 'Invalid Date') {
590
- animeInfo.startDate = {
591
- day: startDate.getDate(),
592
- month: startDate.getMonth(),
593
- year: startDate.getFullYear(),
594
- };
595
- }
596
-
597
- if (endDate.toString() !== 'Invalid Date') {
598
- animeInfo.endDate = {
599
- day: endDate.getDate(),
600
- month: endDate.getMonth(),
601
- year: endDate.getFullYear(),
602
- };
603
- }
604
- }
605
-
606
- break;
607
-
608
- case 'score':
609
- animeInfo.rating = parseFloat(value);
610
- break;
611
- case 'studios':
612
- for (const studio of $(elem).find('a')) animeInfo.studios?.push($(studio).text());
613
- break;
614
- case 'rating':
615
- animeInfo.ageRating = value;
616
- }
617
- });
618
-
619
- // Only works on certain animes, so it is unreliable
620
- // let videoLink = $('.mt4.ar a').attr('href');
621
- // if (videoLink) {
622
- // await this.populateEpisodeList(episodes, videoLink);
623
- // }
624
- return animeInfo;
625
- };
626
- }
627
-
628
- export default Myanimelist;
629
-
630
- // (async () => {
631
- // const mal = new Myanimelist();
632
- // // const search = await mal.search('one piece');
633
- // const info = await mal.fetchAnimeInfo('21', true);
634
- // //console.log(info);
635
- // })();
1
+ import axios from 'axios';
2
+ import { load } from 'cheerio';
3
+
4
+ import {
5
+ AnimeParser,
6
+ type ISearch,
7
+ type IAnimeInfo,
8
+ MediaStatus,
9
+ type IAnimeResult,
10
+ type ISource,
11
+ type IAnimeEpisode,
12
+ SubOrDub,
13
+ type IEpisodeServer,
14
+ MediaFormat,
15
+ } from '../../models';
16
+ import { substringAfter, substringBefore, calculateStringSimilarity, kitsuSearchQuery, range } from '../../utils';
17
+ import Zoro from '../anime/zoro/zoro';
18
+ import Anify from '../anime/anify';
19
+ import { ANIFY_URL } from '../../utils/utils';
20
+
21
+ class Myanimelist extends AnimeParser {
22
+ override readonly name = 'Myanimelist';
23
+ protected override baseUrl = 'https://myanimelist.net/';
24
+ protected override logo = 'https://en.wikipedia.org/wiki/MyAnimeList#/media/File:MyAnimeList.png';
25
+ protected override classPath = 'META.Myanimelist';
26
+
27
+ private readonly anilistGraphqlUrl = 'https://graphql.anilist.co';
28
+ private readonly kitsuGraphqlUrl = 'https://kitsu.app/api/graphql';
29
+ private readonly malSyncUrl = 'https://api.malsync.moe';
30
+ private readonly anifyUrl = ANIFY_URL;
31
+ provider: AnimeParser;
32
+
33
+ /**
34
+ * This class maps myanimelist to kitsu with any other anime provider.
35
+ * kitsu is used for episode images, titles and description.
36
+ * @param provider anime provider (optional) default: Gogoanime
37
+ */
38
+ constructor(provider?: AnimeParser) {
39
+ super();
40
+ this.provider = provider || new Zoro();
41
+ }
42
+
43
+ private malStatusToMediaStatus(status: string): MediaStatus {
44
+ if (status === 'currently airing') return MediaStatus.ONGOING;
45
+ else if (status === 'finished airing') return MediaStatus.COMPLETED;
46
+ else if (status === 'not yet aired') return MediaStatus.NOT_YET_AIRED;
47
+ return MediaStatus.UNKNOWN;
48
+ }
49
+
50
+ private async populateEpisodeList(episodes: IAnimeEpisode[], url: string, count: number = 1): Promise<void> {
51
+ try {
52
+ const { data } = await axios.request({
53
+ method: 'get',
54
+ url: `${url}?p=${count}`,
55
+ headers: {
56
+ 'user-agent':
57
+ 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36 Edg/107.0.1418.35',
58
+ },
59
+ });
60
+
61
+ let hasEpisodes = false;
62
+ const $ = load(data);
63
+ for (const elem of $('.video-list').toArray()) {
64
+ const href = $(elem).attr('href');
65
+ const image = $(elem).find('img').attr('data-src');
66
+ const titleDOM = $(elem).find('.episode-title');
67
+ const title = titleDOM?.text();
68
+ titleDOM.remove();
69
+
70
+ const numberDOM = $(elem).find('.title').text().split(' ');
71
+ let number = 0;
72
+ if (numberDOM.length > 1) {
73
+ number = Number(numberDOM[1]);
74
+ }
75
+ if (href && href.indexOf('myanimelist.net/anime') > -1) {
76
+ hasEpisodes = true;
77
+ episodes.push({
78
+ id: '',
79
+ number,
80
+ title,
81
+ image,
82
+ });
83
+ }
84
+ }
85
+
86
+ if (hasEpisodes) await this.populateEpisodeList(episodes, url, ++count);
87
+ } catch (err) {
88
+ console.error(err);
89
+ }
90
+ }
91
+
92
+ override search = async (query: string, page: number = 1): Promise<ISearch<IAnimeResult>> => {
93
+ const searchResults: ISearch<IAnimeResult> = {
94
+ currentPage: page,
95
+ results: [],
96
+ };
97
+
98
+ const { data } = await axios.request({
99
+ method: 'get',
100
+ url: `https://myanimelist.net/anime.php?q=${query}&cat=anime&show=${50 * (page - 1)}`,
101
+ headers: {
102
+ 'user-agent':
103
+ 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36 Edg/107.0.1418.35',
104
+ },
105
+ });
106
+
107
+ const $ = load(data);
108
+
109
+ const pages = $('.normal_header').find('span').children();
110
+ const maxPage = parseInt(pages.last().text());
111
+ const hasNextPage = page < maxPage;
112
+ searchResults.hasNextPage = hasNextPage;
113
+
114
+ $('tr').each((i, item) => {
115
+ const id = $(item).find('.hoverinfo_trigger').attr('href')?.split('anime/')[1]!.split('/')[0];
116
+ const title = $(item).find('strong').text();
117
+ const description = $(item).find('.pt4').text().replace('...read more.', '...');
118
+ const type = $(item).children().eq(2).text().trim();
119
+ const episodeCount = $(item).children().eq(3).text().trim();
120
+ const score = (parseFloat($(item).children().eq(4).text()) * 10).toFixed(0);
121
+ const imageTmp = $(item).children().first().find('img').attr('data-src');
122
+ const imageUrl = `https://cdn.myanimelist.net/images/anime/${imageTmp?.split('anime/')[1]}`;
123
+
124
+ if (title !== '') {
125
+ searchResults.results.push({
126
+ id: id ?? '',
127
+ title: title,
128
+ image: imageUrl,
129
+ rating: parseInt(score),
130
+ description: description,
131
+ totalEpisodes: parseInt(episodeCount),
132
+ type:
133
+ type === 'TV'
134
+ ? MediaFormat.TV
135
+ : type === 'TV_SHORT'
136
+ ? MediaFormat.TV_SHORT
137
+ : type === 'MOVIE'
138
+ ? MediaFormat.MOVIE
139
+ : type === 'SPECIAL'
140
+ ? MediaFormat.SPECIAL
141
+ : type === 'OVA'
142
+ ? MediaFormat.OVA
143
+ : type === 'ONA'
144
+ ? MediaFormat.ONA
145
+ : type === 'MUSIC'
146
+ ? MediaFormat.MUSIC
147
+ : type === 'MANGA'
148
+ ? MediaFormat.MANGA
149
+ : type === 'NOVEL'
150
+ ? MediaFormat.NOVEL
151
+ : type === 'ONE_SHOT'
152
+ ? MediaFormat.ONE_SHOT
153
+ : undefined,
154
+ });
155
+ }
156
+ });
157
+
158
+ return searchResults;
159
+ };
160
+
161
+ /**
162
+ *
163
+ * @param animeId anime id
164
+ * @param fetchFiller fetch filler episodes
165
+ */
166
+ fetchAnimeInfo = async (animeId: string, dub: boolean = false, fetchFiller: boolean = false): Promise<IAnimeInfo> => {
167
+ try {
168
+ const animeInfo = await this.fetchMalInfoById(animeId);
169
+
170
+ const titleWithLanguages = animeInfo?.title as {
171
+ english: string;
172
+ romaji: string;
173
+ native: string;
174
+ userPreferred: string;
175
+ };
176
+ let fillerEpisodes: { 'number': string; 'filler-bool': boolean }[];
177
+ if (
178
+ this.provider instanceof Zoro &&
179
+ !dub &&
180
+ (animeInfo.status === MediaStatus.ONGOING ||
181
+ range({ from: 2000, to: new Date().getFullYear() + 1 }).includes(animeInfo.startDate?.year!))
182
+ ) {
183
+ try {
184
+ animeInfo.episodes = (
185
+ await new Anify(
186
+ undefined,
187
+ undefined,
188
+ this.provider.name.toLowerCase() as 'gogoanime' | 'zoro' | '9anime' | 'animepahe'
189
+ ).fetchAnimeInfo(animeId)
190
+ ).episodes?.map((item: any) => ({
191
+ id: item.slug,
192
+ title: item.title,
193
+ description: item.description,
194
+ number: item.number,
195
+ image: item.image,
196
+ }));
197
+ animeInfo.episodes?.reverse();
198
+ } catch (err) {
199
+ animeInfo.episodes = await this.findAnimeSlug(
200
+ titleWithLanguages?.english ||
201
+ titleWithLanguages?.romaji ||
202
+ titleWithLanguages?.native ||
203
+ titleWithLanguages?.userPreferred,
204
+ animeInfo.season!,
205
+ animeInfo.startDate?.year!,
206
+ animeId,
207
+ dub
208
+ );
209
+
210
+ animeInfo.episodes = animeInfo.episodes?.map((episode: IAnimeEpisode) => {
211
+ if (!episode.image) episode.image = animeInfo.image;
212
+
213
+ return episode;
214
+ });
215
+
216
+ return animeInfo;
217
+ }
218
+ } else
219
+ animeInfo.episodes = await this.findAnimeSlug(
220
+ titleWithLanguages?.english ||
221
+ titleWithLanguages?.romaji ||
222
+ titleWithLanguages?.native ||
223
+ titleWithLanguages?.userPreferred,
224
+ animeInfo.season!,
225
+ animeInfo.startDate?.year!,
226
+ animeId,
227
+ dub
228
+ );
229
+
230
+ if (fetchFiller) {
231
+ const { data: fillerData } = await axios({
232
+ baseURL: `https://raw.githubusercontent.com/saikou-app/mal-id-filler-list/main/fillers/${animeId}.json`,
233
+ method: 'GET',
234
+ validateStatus: () => true,
235
+ });
236
+
237
+ if (!fillerData.toString().startsWith('404')) {
238
+ fillerEpisodes = [];
239
+ fillerEpisodes?.push(
240
+ ...(fillerData.episodes as {
241
+ 'number': string;
242
+ 'filler-bool': boolean;
243
+ }[])
244
+ );
245
+ }
246
+ }
247
+
248
+ animeInfo.episodes = animeInfo.episodes?.map((episode: IAnimeEpisode) => {
249
+ if (!episode.image) episode.image = animeInfo.image;
250
+
251
+ if (fetchFiller && fillerEpisodes?.length > 0 && fillerEpisodes?.length >= animeInfo.episodes!.length) {
252
+ if (fillerEpisodes[episode.number! - 1])
253
+ episode.isFiller = new Boolean(fillerEpisodes?.[episode.number! - 1]!['filler-bool']).valueOf();
254
+ }
255
+
256
+ return episode;
257
+ });
258
+
259
+ return animeInfo;
260
+ } catch (err) {
261
+ console.error(err);
262
+ throw err;
263
+ }
264
+ };
265
+
266
+ override fetchEpisodeSources = async (episodeId: string, ...args: any): Promise<ISource> => {
267
+ try {
268
+ if (episodeId.includes('/') && this.provider instanceof Anify)
269
+ return new Anify().fetchEpisodeSources(episodeId, args[0], args[1]);
270
+ return this.provider.fetchEpisodeSources(episodeId, ...args);
271
+ } catch (err) {
272
+ throw new Error(`Failed to fetch episode sources from ${this.provider.name}: ${err}`);
273
+ }
274
+ };
275
+
276
+ fetchEpisodeServers(episodeId: string): Promise<IEpisodeServer[]> {
277
+ return this.provider.fetchEpisodeServers(episodeId);
278
+ }
279
+
280
+ private findAnimeRaw = async (slug: string, externalLinks?: any) => {
281
+ const findAnime = (await this.provider.search(slug)) as ISearch<IAnimeResult>;
282
+ if (findAnime.results.length === 0) return [];
283
+
284
+ // Sort the retrieved info for more accurate results.
285
+
286
+ findAnime.results.sort((a, b) => {
287
+ const targetTitle = slug.toLowerCase();
288
+
289
+ let firstTitle: string;
290
+ let secondTitle: string;
291
+
292
+ if (typeof a.title === 'string') firstTitle = a.title as string;
293
+ else firstTitle = a.title.english ?? a.title.romaji ?? '';
294
+
295
+ if (typeof b.title === 'string') secondTitle = b.title as string;
296
+ else secondTitle = b.title.english ?? b.title.romaji ?? '';
297
+
298
+ const firstRating = calculateStringSimilarity(targetTitle, firstTitle.toLowerCase());
299
+ const secondRating = calculateStringSimilarity(targetTitle, secondTitle.toLowerCase());
300
+
301
+ // Sort in descending order
302
+ return secondRating - firstRating;
303
+ });
304
+
305
+ // TODO: use much better way than this
306
+ return (await this.provider.fetchAnimeInfo(findAnime.results[0]!.id)) as IAnimeInfo;
307
+ };
308
+
309
+ private findAnimeSlug = async (
310
+ title: string,
311
+ season: string,
312
+ startDate: number,
313
+ malId: string,
314
+ dub: boolean,
315
+ externalLinks?: any
316
+ ): Promise<IAnimeEpisode[]> => {
317
+ if (this.provider instanceof Anify) return (await this.provider.fetchAnimeInfo(malId)).episodes!;
318
+
319
+ // console.log({ title });
320
+ const slug = title?.replace(/[^0-9a-zA-Z]+/g, ' ');
321
+
322
+ let possibleAnime: any | undefined;
323
+
324
+ possibleAnime = await this.findAnimeRaw(slug, externalLinks);
325
+
326
+ // To avoid a new request, lets match and see if the anime show found is in sub/dub
327
+
328
+ const expectedType = dub ? SubOrDub.DUB : SubOrDub.SUB;
329
+
330
+ if (possibleAnime.subOrDub !== SubOrDub.BOTH && possibleAnime.subOrDub !== expectedType) {
331
+ return [];
332
+ }
333
+
334
+ if (this.provider instanceof Zoro) {
335
+ // Set the correct episode sub/dub request type
336
+ possibleAnime.episodes.forEach((_: any, index: number) => {
337
+ if (possibleAnime.subOrDub === SubOrDub.BOTH) {
338
+ possibleAnime.episodes[index].id = possibleAnime.episodes[index].id.replace(`$both`, dub ? '$dub' : '$sub');
339
+ }
340
+ });
341
+ }
342
+
343
+ const possibleProviderEpisodes = possibleAnime.episodes as IAnimeEpisode[];
344
+
345
+ if (
346
+ typeof possibleProviderEpisodes[0]?.image !== 'undefined' &&
347
+ typeof possibleProviderEpisodes[0]?.title !== 'undefined' &&
348
+ typeof possibleProviderEpisodes[0]?.description !== 'undefined'
349
+ )
350
+ return possibleProviderEpisodes;
351
+
352
+ const options = {
353
+ headers: { 'Content-Type': 'application/json' },
354
+ query: kitsuSearchQuery(slug),
355
+ };
356
+
357
+ const newEpisodeList = await this.findKitsuAnime(possibleProviderEpisodes, options, season, startDate);
358
+
359
+ return newEpisodeList;
360
+ };
361
+
362
+ private findKitsuAnime = async (
363
+ possibleProviderEpisodes: IAnimeEpisode[],
364
+ options: {},
365
+ season?: string,
366
+ startDate?: number
367
+ ) => {
368
+ const kitsuEpisodes = await axios.post(this.kitsuGraphqlUrl, options);
369
+ const episodesList = new Map();
370
+ if (kitsuEpisodes?.data.data) {
371
+ const { nodes } = kitsuEpisodes.data.data.searchAnimeByTitle;
372
+
373
+ if (nodes) {
374
+ nodes.forEach((node: any) => {
375
+ if (node.season === season && node.startDate.trim().split('-')[0] === startDate?.toString()) {
376
+ const episodes = node.episodes.nodes;
377
+
378
+ for (const episode of episodes) {
379
+ const i = episode?.number.toString().replace(/"/g, '');
380
+ let name;
381
+ let description;
382
+ let thumbnail;
383
+
384
+ if (episode?.description?.en)
385
+ description = episode?.description.en.toString().replace(/"/g, '').replace('\\n', '\n');
386
+ if (episode?.thumbnail) thumbnail = episode?.thumbnail.original.url.toString().replace(/"/g, '');
387
+
388
+ if (episode) {
389
+ if (episode.titles?.canonical) name = episode.titles.canonical.toString().replace(/"/g, '');
390
+ episodesList.set(i, {
391
+ episodeNum: episode?.number.toString().replace(/"/g, ''),
392
+ title: name,
393
+ description,
394
+ thumbnail,
395
+ });
396
+ continue;
397
+ }
398
+ episodesList.set(i, {
399
+ episodeNum: undefined,
400
+ title: undefined,
401
+ description: undefined,
402
+ thumbnail,
403
+ });
404
+ }
405
+ }
406
+ });
407
+ }
408
+ }
409
+
410
+ const newEpisodeList: IAnimeEpisode[] = [];
411
+ if (possibleProviderEpisodes?.length !== 0) {
412
+ possibleProviderEpisodes?.forEach((ep: any, i: any) => {
413
+ const j = (i + 1).toString();
414
+ newEpisodeList.push({
415
+ id: ep.id as string,
416
+ title: ep.title ?? episodesList.get(j)?.title ?? null,
417
+ image: ep.image ?? episodesList.get(j)?.thumbnail ?? null,
418
+ number: ep.number as number,
419
+ description: ep.description ?? episodesList.get(j)?.description ?? null,
420
+ url: (ep.url as string) ?? null,
421
+ });
422
+ });
423
+ }
424
+
425
+ return newEpisodeList;
426
+ };
427
+
428
+ /**
429
+ *
430
+ * @param id anime id
431
+ * @returns anime info without streamable episodes
432
+ */
433
+ fetchMalInfoById = async (id: string): Promise<IAnimeInfo> => {
434
+ const animeInfo: IAnimeInfo = {
435
+ id: id,
436
+ title: '',
437
+ };
438
+
439
+ const { data } = await axios.request({
440
+ method: 'GET',
441
+ url: `https://myanimelist.net/anime/${id}`,
442
+ headers: {
443
+ 'user-agent':
444
+ 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36 Edg/107.0.1418.35',
445
+ },
446
+ });
447
+
448
+ const $ = load(data);
449
+ const episodes: IAnimeEpisode[] = [];
450
+ const desc = $('[itemprop="description"]').first().text();
451
+ const imageElem = $('[itemprop="image"]').first();
452
+ const image = imageElem.attr('src') || imageElem.attr('data-image') || imageElem.attr('data-src');
453
+ const genres: string[] = [];
454
+ const genreDOM = $('[itemprop="genre"]').get();
455
+
456
+ genreDOM.forEach((elem) => genres.push($(elem).text()));
457
+
458
+ animeInfo.genres = genres;
459
+ animeInfo.image = image;
460
+ animeInfo.description = desc;
461
+ animeInfo.title = {
462
+ english: $('.js-alternative-titles.hide').children().eq(0).text().replace('English: ', '').trim(),
463
+ romaji: $('.title-name').text(),
464
+ native: $('.js-alternative-titles.hide').parent().children().eq(9).text().trim(),
465
+ userPreferred: $('.js-alternative-titles.hide').children().eq(0).text().replace('English: ', '').trim(),
466
+ };
467
+
468
+ animeInfo.synonyms = $('.js-alternative-titles.hide')
469
+ .parent()
470
+ .children()
471
+ .eq(8)
472
+ .text()
473
+ .replace('Synonyms:', '')
474
+ .trim()
475
+ .split(',');
476
+ animeInfo.studios = [];
477
+ animeInfo.popularity = parseInt($('.numbers.popularity').text().trim().replace('Popularity #', '').trim());
478
+
479
+ const producers: string[] = [];
480
+ $('a').each(function (i: number, link: any) {
481
+ if ($(link).attr('href')?.includes('producer') && $(link).parent().children().eq(0).text() === 'Producers:') {
482
+ producers.push($(link).text());
483
+ }
484
+ });
485
+ animeInfo.producers = producers;
486
+ // animeInfo.episodes = episodes;
487
+
488
+ const teaserDOM = $('.video-promotion > a');
489
+ if (teaserDOM.length > 0) {
490
+ const teaserURL = $(teaserDOM).attr('href');
491
+ const style = $(teaserDOM).attr('style');
492
+ if (teaserURL) {
493
+ animeInfo.trailer = {
494
+ id: substringAfter(teaserURL, 'embed/').split('?')[0]!,
495
+ site: 'https://youtube.com/watch?v=',
496
+ thumbnail: style ? substringBefore(substringAfter(style, "url('"), "'") : '',
497
+ };
498
+ }
499
+ }
500
+ const ops = $('.theme-songs.js-theme-songs.opnening').find('tr').get();
501
+
502
+ const ignoreList = ['Apple Music', 'Youtube Music', 'Amazon Music', 'Spotify'];
503
+ animeInfo.openings = ops.map((element: any) => {
504
+ //console.log($(element).text().trim());
505
+ const name = $(element).children().eq(1).children().first().text().trim();
506
+ if (!ignoreList.includes(name)) {
507
+ if ($(element).find('.theme-song-index').length !== 0) {
508
+ const index = $(element).find('.theme-song-index').text().trim();
509
+ const band = $(element).find('.theme-song-artist').text().trim();
510
+ const episodes = $(element).find('.theme-song-episode').text().trim();
511
+ //console.log($(element).children().eq(1).text().trim().split(index)[1]);
512
+
513
+ return {
514
+ name: $(element).children().eq(1).text().trim().split(index)[1]?.split(band)[0]?.trim(),
515
+ band: band.replace('by ', ''),
516
+ episodes: episodes,
517
+ };
518
+ } else {
519
+ const band = $(element).find('.theme-song-artist').text().trim();
520
+ const episodes = $(element).find('.theme-song-episode').text().trim();
521
+ return {
522
+ name: $(element).children().eq(1).text().trim()?.split(band)[0]?.trim(),
523
+ band: band.replace('by ', ''),
524
+ episodes: episodes,
525
+ };
526
+ }
527
+ }
528
+ });
529
+ animeInfo.openings = (animeInfo.openings as any[]).filter(function (element: any) {
530
+ return element !== undefined;
531
+ });
532
+
533
+ const eds = $('.theme-songs.js-theme-songs.ending').find('tr').get();
534
+ animeInfo.endings = eds.map((element: any) => {
535
+ //console.log($(element).text().trim());
536
+ const name = $(element).children().eq(1).children().first().text().trim();
537
+ if (!ignoreList.includes(name)) {
538
+ if ($(element).find('.theme-song-index').length !== 0) {
539
+ const index = $(element).find('.theme-song-index').text().trim();
540
+ const band = $(element).find('.theme-song-artist').text().trim();
541
+ const episodes = $(element).find('.theme-song-episode').text().trim();
542
+ //console.log($(element).children().eq(1).text().trim().split(index)[1]);
543
+
544
+ return {
545
+ name: $(element).children().eq(1).text().trim().split(index)[1]?.split(band)[0]?.trim(),
546
+ band: band.replace('by ', ''),
547
+ episodes: episodes,
548
+ };
549
+ } else {
550
+ const band = $(element).find('.theme-song-artist').text().trim();
551
+ const episodes = $(element).find('.theme-song-episode').text().trim();
552
+ return {
553
+ name: $(element).children().eq(1).text().trim()?.split(band)[0]?.trim(),
554
+ band: band.replace('by ', ''),
555
+ episodes: episodes,
556
+ };
557
+ }
558
+ }
559
+ });
560
+ animeInfo.endings = (animeInfo.endings as any[]).filter(function (element: any) {
561
+ return element !== undefined;
562
+ });
563
+
564
+ const description = $('.spaceit_pad').get();
565
+
566
+ description.forEach((elem: any) => {
567
+ const text = $(elem).text().toLowerCase().trim();
568
+ const key = text.split(':')[0];
569
+ const value = substringAfter(text, `${key}:`).trim();
570
+ switch (key) {
571
+ case 'status':
572
+ animeInfo.status = this.malStatusToMediaStatus(value);
573
+ break;
574
+ case 'episodes':
575
+ animeInfo.totalEpisodes = parseInt(value);
576
+ if (isNaN(animeInfo.totalEpisodes)) animeInfo.totalEpisodes = 0;
577
+ break;
578
+ case 'premiered':
579
+ animeInfo.season = value.split(' ')[0]?.toUpperCase();
580
+ break;
581
+ case 'aired':
582
+ const dates = value.split('to');
583
+ if (dates.length >= 2) {
584
+ const start = dates[0]?.trim();
585
+ const end = dates[1]?.trim();
586
+ const startDate = new Date(start!);
587
+ const endDate = new Date(end!);
588
+
589
+ if (startDate.toString() !== 'Invalid Date') {
590
+ animeInfo.startDate = {
591
+ day: startDate.getDate(),
592
+ month: startDate.getMonth(),
593
+ year: startDate.getFullYear(),
594
+ };
595
+ }
596
+
597
+ if (endDate.toString() !== 'Invalid Date') {
598
+ animeInfo.endDate = {
599
+ day: endDate.getDate(),
600
+ month: endDate.getMonth(),
601
+ year: endDate.getFullYear(),
602
+ };
603
+ }
604
+ }
605
+
606
+ break;
607
+
608
+ case 'score':
609
+ animeInfo.rating = parseFloat(value);
610
+ break;
611
+ case 'studios':
612
+ for (const studio of $(elem).find('a')) animeInfo.studios?.push($(studio).text());
613
+ break;
614
+ case 'rating':
615
+ animeInfo.ageRating = value;
616
+ }
617
+ });
618
+
619
+ // Only works on certain animes, so it is unreliable
620
+ // let videoLink = $('.mt4.ar a').attr('href');
621
+ // if (videoLink) {
622
+ // await this.populateEpisodeList(episodes, videoLink);
623
+ // }
624
+ return animeInfo;
625
+ };
626
+ }
627
+
628
+ export default Myanimelist;
629
+
630
+ // (async () => {
631
+ // const mal = new Myanimelist();
632
+ // // const search = await mal.search('one piece');
633
+ // const info = await mal.fetchAnimeInfo('21', true);
634
+ // //console.log(info);
635
+ // })();