├── .github ├── FUNDING.yml └── workflows │ └── deploy.yml ├── .gitignore ├── Dockerfile ├── LICENSE ├── README.md ├── config.js ├── package-lock.json ├── package.json ├── scripts └── bump-version.js ├── src ├── helpers │ ├── apiRequestRawHtml.js │ ├── cache.js │ ├── getTitle.js │ └── seriesFetcher.js ├── index.js └── routes │ ├── index.js │ ├── reviews.js │ ├── search.js │ ├── title.js │ └── user │ ├── index.js │ ├── info.js │ └── rating.js ├── tests ├── search.test.js └── title.test.js └── wrangler.toml /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | github: [tuhinpal] 2 | -------------------------------------------------------------------------------- /.github/workflows/deploy.yml: -------------------------------------------------------------------------------- 1 | name: Deploy to Cloudflare Worker 2 | 3 | on: 4 | push: 5 | branches: [ "master" ] 6 | repository_dispatch: 7 | 8 | jobs: 9 | build: 10 | runs-on: ubuntu-latest 11 | 12 | strategy: 13 | matrix: 14 | node-version: [ 18.x ] 15 | 16 | steps: 17 | - uses: actions/checkout@v3 18 | 19 | - name: Use Node.js ${{ matrix.node-version }} 20 | uses: actions/setup-node@v3 21 | with: 22 | node-version: ${{ matrix.node-version }} 23 | 24 | - name: Deploy 25 | run: | 26 | npm install 27 | npm run publish 28 | env: 29 | CLOUDFLARE_API_TOKEN: ${{ secrets.CF_API_TOKEN }} 30 | CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CF_ACCOUNT_ID }} 31 | 32 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | /dist 3 | **/*.rs.bk 4 | Cargo.lock 5 | bin/ 6 | pkg/ 7 | wasm-pack.log 8 | worker/ 9 | node_modules/ 10 | .cargo-ok 11 | .mf 12 | .wrangler -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM node:alpine 2 | WORKDIR /app 3 | COPY package*.json . 4 | RUN npm install 5 | COPY . . 6 | EXPOSE 3000 7 | CMD [ "npm", "start" ] -------------------------------------------------------------------------------- /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 | ## Important Update: Project Discontinued 🔔 2 | 3 | IMDb has recently launched their [official API](https://developer.imdb.com/), providing developers with authorized access to their database. Given this development, I've made the decision to discontinue maintenance of this project for the following reasons: 4 | 5 | 1. To avoid potential conflicts with IMDb's terms of service and intellectual property rights. 6 | 2. To encourage the use of officially supported and maintained data sources. 7 | 8 | Recommendations for users of this project: 9 | 10 | 1. Transition to IMDb's official API for the most up-to-date and reliable movie data. 11 | 2. Consider using alternative sources like TMDB (The Movie Database) API as another robust option. 12 | 13 | This repository will be archived to preserve the code for reference purposes. Thank you to all contributors and users for your support throughout this project's lifespan. 14 | 15 | For any questions or concerns, please refer to IMDb's developer documentation or explore TMDB's API offerings. 16 | 17 | ![IMDB API](https://user-images.githubusercontent.com/51857187/170807293-a52d8141-f743-4501-82e5-55e3d4286e61.jpg) 18 | 19 | ## Features 🪶 20 | 21 | - Search titles 22 | - Search by IMDB ID 23 | - Cacheable Result 24 | - High Performance 25 | - Get episode information 26 | - Get all reviews with full pagination supported 27 | 28 | ## Installation 📦 29 | 30 | If you anticipate sending a large number of requests, it is recommended that you deploy your own Cloudflare worker. Installation is pretty easy and straight forward. Click the button below to get started. 31 | 32 | [![Deploy to Cloudflare Workers](https://deploy.workers.cloudflare.com/button)](https://deploy.workers.cloudflare.com/?url=https://github.com/tuhinpal/imdb-api) 33 | 34 | After deployed, map the worker to a Domain Name to configure cache. Only Workers deployed to custom domains have access to functional cache operations. 35 | 36 | ## Run with docker 🐋 37 | 38 | - Clone this repository 39 | - Build the image 40 | ``` 41 | docker build -t imdb-api . 42 | ``` 43 | - Start the process (Deatached) 44 | ``` 45 | docker run -p 3000:3000 -it -d imdb-api 46 | ``` 47 | 48 | ## API 📡 49 | 50 | [![Run in Postman](https://run.pstmn.io/button.svg)](https://app.getpostman.com/run-collection/12162111-12f08f8e-a76b-4cf4-a7b9-17cb9f95dd82?action=collection%2Ffork&collection-url=entityId%3D12162111-12f08f8e-a76b-4cf4-a7b9-17cb9f95dd82%26entityType%3Dcollection%26workspaceId%3D7efe0056-efcd-49b1-bfd8-0854d36c1065) 51 | 52 | | Endpoint | Method | Description | Example | 53 | | ------------------------------------------------------------------------------------------------ | ------ | ----------------------------------------- | --------------------------------------------------------------------------------------------- | 54 | | `/search?query={query}` | GET | Search titles by title | [Try It](https://imdb-api.projects.thetuhin.com/search?query=Little%20Things) | 55 | | `/title/{imdb_id}` | GET | Get details of a title | [Try It](https://imdb-api.projects.thetuhin.com/title/tt6522580) | 56 | | `/reviews/{imdb_id}?option={helpfulness\|date\|votes\|rating}&sortOrder={asc\|desc}` | GET | Get reviews of a title | [Try It](https://imdb-api.projects.thetuhin.com/reviews/tt6522580?option=date&sortOrder=desc) | 57 | | `/title/{imdb_id}/season/{season_id}` | GET | (New) Fetch a single season of a series | [Try It](https://imdb-api.projects.thetuhin.com/title/tt6522580/season/4) | 58 | | `/user/{user_id}` | GET | (New) Fetch an user's info | [Try It](https://imdb-api.projects.thetuhin.com/user/ur82525142) | 59 | | `/user/{user_id}/ratings?ratingFilter={1-10}&sort={most_recent\|oldest\|top_rated\|worst_rated}` | GET | (New) Fetch an user's ratings and reviews | [Try It](https://imdb-api.projects.thetuhin.com/user/ur82525142/ratings) | 60 | 61 | ## License 🎯 62 | 63 | - Licensed under [Apache-2.0](https://github.com/tuhinpal/imdb-api/blob/master/LICENSE) 64 | - Made by [Tuhin Kanti Pal](https://github.com/tuhinpal) 65 | 66 | ### Have a good day 🤘 67 | -------------------------------------------------------------------------------- /config.js: -------------------------------------------------------------------------------- 1 | export default { 2 | cacheDisabled: false, 3 | }; 4 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "private": true, 3 | "name": "imdb-api", 4 | "version": "1.0.3", 5 | "description": "Serverless IMDB API powered by Cloudflare Worker", 6 | "main": "src/index.js", 7 | "scripts": { 8 | "dev": "wrangler dev src/index.js --port 3000", 9 | "publish": "wrangler deploy src/index.js", 10 | "test": "jest", 11 | "start": "wrangler dev src/index.js --port 3000", 12 | "bump": "node scripts/bump-version.js" 13 | }, 14 | "author": "tuhinpal ", 15 | "license": "Apache-2.0", 16 | "devDependencies": { 17 | "axios": "^0.27.2", 18 | "jest": "^28.1.0", 19 | "wrangler": "^3.3.0" 20 | }, 21 | "dependencies": { 22 | "dom-parser": "^0.1.6", 23 | "hono": "^1.4.1", 24 | "html-entities": "^2.3.3", 25 | "qs": "^6.11.1" 26 | }, 27 | "directories": { 28 | "test": "tests" 29 | }, 30 | "repository": { 31 | "type": "git", 32 | "url": "git+https://github.com/tuhinpal/imdb-api.git" 33 | }, 34 | "keywords": [ 35 | "imdb", 36 | "imdb-api", 37 | "movie-list", 38 | "cloudflare-worker", 39 | "cloudflare-workers" 40 | ], 41 | "bugs": { 42 | "url": "https://github.com/tuhinpal/imdb-api/issues" 43 | }, 44 | "homepage": "https://github.com/tuhinpal/imdb-api#readme" 45 | } -------------------------------------------------------------------------------- /scripts/bump-version.js: -------------------------------------------------------------------------------- 1 | const fs = require("fs"); 2 | const packagejson = require("../package.json"); 3 | const { exec } = require("child_process"); 4 | 5 | function bumpVersion(current = "") { 6 | const splitted = current.split("."); 7 | let currentVersion = parseInt(splitted.join("")); 8 | currentVersion++; 9 | const newVersion = currentVersion.toString().split("").join("."); 10 | return newVersion; 11 | } 12 | 13 | const newVersion = bumpVersion(packagejson.version); 14 | 15 | console.log(`Bumping version from ${packagejson.version} to ${newVersion}...`); 16 | 17 | packagejson.version = newVersion; 18 | fs.writeFileSync("./package.json", JSON.stringify(packagejson, null, 2)); 19 | 20 | console.log("Running npm install..."); 21 | exec("npm install", (err, stdout, stderr) => { 22 | if (err) { 23 | console.log(err); 24 | return; 25 | } 26 | 27 | console.log("Installed dependencies"); 28 | console.log(`Bumped version to ${newVersion}!`); 29 | }); 30 | -------------------------------------------------------------------------------- /src/helpers/apiRequestRawHtml.js: -------------------------------------------------------------------------------- 1 | export default async function apiRequestRawHtml(url) { 2 | let data = await fetch(url, { 3 | headers: { 4 | "User-Agent": 5 | "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36", 6 | accept: "text/html", 7 | "accept-language": "en-US", 8 | }, 9 | }); 10 | let text = await data.text(); 11 | return text; 12 | } 13 | 14 | export async function apiRequestJson(url) { 15 | let data = await fetch(url, { 16 | headers: { 17 | "User-Agent": 18 | "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36", 19 | accept: "text/html", 20 | "accept-language": "en-US", 21 | }, 22 | }); 23 | let text = await data.json(); 24 | return text; 25 | } 26 | -------------------------------------------------------------------------------- /src/helpers/cache.js: -------------------------------------------------------------------------------- 1 | import config from "../../config"; 2 | 3 | export default async function cache(c, next) { 4 | const key = c.req.url; 5 | const cache = await caches.default; 6 | const response = await cache.match(key); 7 | 8 | function getCacheTTL() { 9 | try { 10 | let url = key.toString().toLowerCase(); 11 | if (url.includes("/reviews")) return 60 * 60 * 24; 12 | if (url.includes("/title")) return 60 * 60 * 24; 13 | if (url.includes("/search")) return 60 * 60 * 24 * 2; 14 | } catch (_) {} 15 | 16 | return 86400; 17 | } 18 | 19 | if (!response) { 20 | await next(); 21 | 22 | if (c.res.status === 200 && !config.cacheDisabled) { 23 | c.res.headers.append("Cache-Control", `public, max-age=${getCacheTTL()}`); 24 | await cache.put(key, c.res.clone()); 25 | } 26 | 27 | return; 28 | } else { 29 | // it was throwing Immutable error 30 | for (let [key, value] of response.headers.entries()) { 31 | c.res.headers.set(key, value); 32 | } 33 | 34 | return c.json(await response.json()); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/helpers/getTitle.js: -------------------------------------------------------------------------------- 1 | import apiRequestRawHtml from "./apiRequestRawHtml"; 2 | import DomParser from "dom-parser"; 3 | import seriesFetcher from "./seriesFetcher"; 4 | 5 | export default async function getTitle(id) { 6 | const parser = new DomParser(); 7 | const html = await apiRequestRawHtml(`https://www.imdb.com/title/${id}`); 8 | const dom = parser.parseFromString(html); 9 | const nextData = dom.getElementsByAttribute("id", "__NEXT_DATA__"); 10 | const json = JSON.parse(nextData[0].textContent); 11 | 12 | const props = json.props.pageProps; 13 | 14 | const getCredits = (lookFor, v) => { 15 | const result = props.aboveTheFoldData.principalCredits.find( 16 | (e) => e?.category?.id === lookFor 17 | ); 18 | 19 | return result 20 | ? result.credits.map((e) => { 21 | if (v === "2") 22 | return { 23 | id: e.name.id, 24 | name: e.name.nameText.text, 25 | }; 26 | 27 | return e.name.nameText.text; 28 | }) 29 | : []; 30 | }; 31 | 32 | return { 33 | id: id, 34 | review_api_path: `/reviews/${id}`, 35 | imdb: `https://www.imdb.com/title/${id}`, 36 | contentType: props.aboveTheFoldData.titleType.id, 37 | contentRating: props.aboveTheFoldData?.certificate?.rating ?? "N/A", 38 | isSeries: props.aboveTheFoldData.titleType.isSeries, 39 | productionStatus: 40 | props.aboveTheFoldData.productionStatus.currentProductionStage.id, 41 | isReleased: 42 | props.aboveTheFoldData.productionStatus.currentProductionStage.id === 43 | "released", 44 | title: props.aboveTheFoldData.titleText.text, 45 | image: props.aboveTheFoldData.primaryImage.url, 46 | images: props.mainColumnData.titleMainImages.edges 47 | .filter((e) => e.__typename === "ImageEdge") 48 | .map((e) => e.node.url), 49 | plot: props.aboveTheFoldData.plot.plotText.plainText, 50 | runtime: 51 | props.aboveTheFoldData.runtime?.displayableProperty?.value?.plainText ?? 52 | "", 53 | runtimeSeconds: props.aboveTheFoldData.runtime?.seconds ?? 0, 54 | rating: { 55 | count: props.aboveTheFoldData.ratingsSummary?.voteCount ?? 0, 56 | star: props.aboveTheFoldData.ratingsSummary?.aggregateRating ?? 0, 57 | }, 58 | award: { 59 | wins: props.mainColumnData.wins?.total ?? 0, 60 | nominations: props.mainColumnData.nominations?.total ?? 0, 61 | }, 62 | genre: props.aboveTheFoldData.genres.genres.map((e) => e.id), 63 | releaseDetailed: { 64 | date: new Date( 65 | props.aboveTheFoldData.releaseDate.year, 66 | props.aboveTheFoldData.releaseDate.month - 1, 67 | props.aboveTheFoldData.releaseDate.day 68 | ).toISOString(), 69 | day: props.aboveTheFoldData.releaseDate.day, 70 | month: props.aboveTheFoldData.releaseDate.month, 71 | year: props.aboveTheFoldData.releaseDate.year, 72 | releaseLocation: { 73 | country: props.mainColumnData.releaseDate?.country?.text, 74 | cca2: props.mainColumnData.releaseDate?.country?.id, 75 | }, 76 | originLocations: props.mainColumnData.countriesOfOrigin.countries.map( 77 | (e) => ({ 78 | country: e.text, 79 | cca2: e.id, 80 | }) 81 | ), 82 | }, 83 | year: props.aboveTheFoldData.releaseDate.year, 84 | spokenLanguages: props.mainColumnData.spokenLanguages.spokenLanguages.map( 85 | (e) => ({ 86 | language: e.text, 87 | id: e.id, 88 | }) 89 | ), 90 | filmingLocations: props.mainColumnData.filmingLocations.edges.map( 91 | (e) => e.node.text 92 | ), 93 | actors: getCredits("cast"), 94 | actors_v2: getCredits("cast", "2"), 95 | creators: getCredits("creator"), 96 | creators_v2: getCredits("creator", "2"), 97 | directors: getCredits("director"), 98 | directors_v2: getCredits("director", "2"), 99 | writers: getCredits("writer"), 100 | writers_v2: getCredits("writer", "2"), 101 | top_credits: props.aboveTheFoldData.principalCredits.map((e) => ({ 102 | id: e.category.id, 103 | name: e.category.text, 104 | credits: e.credits.map((e) => e.name.nameText.text), 105 | })), 106 | ...(props.aboveTheFoldData.titleType.isSeries 107 | ? await seriesFetcher(id) 108 | : {}), 109 | }; 110 | } 111 | -------------------------------------------------------------------------------- /src/helpers/seriesFetcher.js: -------------------------------------------------------------------------------- 1 | import DomParser from "dom-parser"; 2 | import apiRequestRawHtml from "./apiRequestRawHtml"; 3 | 4 | export default async function seriesFetcher(id) { 5 | try { 6 | const firstSeason = await getSeason({ id, seasonId: 1 }); 7 | 8 | return { 9 | all_seasons: firstSeason.all_seasons, 10 | seasons: [ 11 | { 12 | ...firstSeason, 13 | all_seasons: undefined, 14 | }, 15 | ], 16 | }; 17 | } catch (error) { 18 | return { 19 | all_seasons: [], 20 | seasons: [], 21 | }; 22 | } 23 | } 24 | 25 | export async function getSeason({ id, seasonId }) { 26 | const html = await apiRequestRawHtml( 27 | `https://www.imdb.com/title/${id}/episodes?season=${seasonId}` 28 | ); 29 | 30 | let parser = new DomParser(); 31 | let dom = parser.parseFromString(html); 32 | 33 | const nextData = dom.getElementsByAttribute("id", "__NEXT_DATA__"); 34 | const json = JSON.parse(nextData[0].textContent); 35 | 36 | const episodes = json.props.pageProps.contentData.section.episodes.items; 37 | const seasons = json.props.pageProps.contentData.section.seasons; 38 | 39 | return { 40 | name: json.props.pageProps.contentData.entityMetadata.titleText.text, 41 | episodes: Object.values(episodes).map((e, i) => { 42 | return { 43 | idx: i + 1, 44 | no: e.episode, 45 | title: e.titleText, 46 | image: e.image.url, 47 | image_large: e.image.url, 48 | image_caption: e.image.caption, 49 | plot: e.plot, 50 | publishedDate: new Date( 51 | e.releaseDate.year, 52 | e.releaseDate.month - 1, 53 | e.releaseDate.day 54 | ).toISOString(), 55 | rating: { 56 | count: e.voteCount, 57 | star: e.aggregateRating, 58 | }, 59 | }; 60 | }), 61 | all_seasons: seasons.map((s) => ({ 62 | id: s.value, 63 | name: `Season ${s.value}`, 64 | api_path: `/title/${id}/season/${s.value}`, 65 | })), 66 | }; 67 | } 68 | -------------------------------------------------------------------------------- /src/index.js: -------------------------------------------------------------------------------- 1 | import { Hono } from "hono"; 2 | import { cors } from "hono/cors"; 3 | import index from "./routes/index"; 4 | import reviews from "./routes/reviews"; 5 | import title from "./routes/title"; 6 | import cache from "./helpers/cache"; 7 | import search from "./routes/search"; 8 | import userRoutes from "./routes/user"; 9 | 10 | const app = new Hono(); 11 | 12 | app.use("*", cors()); 13 | app.use("*", cache); 14 | 15 | app.route("/search", search); 16 | app.route("/title", title); 17 | app.route("/reviews", reviews); 18 | app.route("/user", userRoutes); 19 | app.route("/", index); 20 | 21 | app.fire(); 22 | -------------------------------------------------------------------------------- /src/routes/index.js: -------------------------------------------------------------------------------- 1 | import { Hono } from "hono"; 2 | const index = new Hono(); 3 | import packageJson from "../../package.json"; 4 | 5 | index.get("/", async (c) => { 6 | return c.json({ 7 | status: "Running", 8 | name: packageJson.name, 9 | description: packageJson.description, 10 | version: packageJson.version, 11 | repository: packageJson.homepage, 12 | author: packageJson.author, 13 | license: packageJson.license, 14 | postman: 15 | "https://www.postman.com/tuhin-pal/workspace/imdb-api/collection/12162111-12f08f8e-a76b-4cf4-a7b9-17cb9f95dd82?action=share&creator=12162111", 16 | postman_collection_json: 17 | "https://www.getpostman.com/collections/c261b9abc6b2a4b5f1c8", 18 | }); 19 | }); 20 | 21 | export default index; 22 | -------------------------------------------------------------------------------- /src/routes/reviews.js: -------------------------------------------------------------------------------- 1 | import { Hono } from "hono"; 2 | import DomParser from "dom-parser"; 3 | import { decode as entityDecoder } from "html-entities"; 4 | import apiRequestRawHtml from "../helpers/apiRequestRawHtml"; 5 | const reviews = new Hono(); 6 | 7 | reviews.get("/:id", async (c) => { 8 | try { 9 | const id = c.req.param("id"); 10 | let option = optionsMapper[0]; 11 | try { 12 | let getOption = optionsMapper.find( 13 | (option) => option.name === c.req.query("option") 14 | ); 15 | if (getOption) option = getOption; 16 | } catch (_) {} 17 | 18 | let sortOrder = c.req.query("sortOrder") === "asc" ? "asc" : "desc"; 19 | let nextKey = c.req.query("nextKey"); 20 | 21 | let reviews = []; 22 | 23 | let parser = new DomParser(); 24 | let rawHtml = await apiRequestRawHtml( 25 | `https://www.imdb.com/title/${id}/reviews/_ajax?sort=${ 26 | option.key 27 | }&dir=${sortOrder}${nextKey ? `&paginationKey=${nextKey}` : ""}` 28 | ); 29 | let dom = parser.parseFromString(rawHtml); 30 | 31 | let item = dom.getElementsByClassName("imdb-user-review"); 32 | 33 | item.forEach((node) => { 34 | try { 35 | let review = {}; 36 | 37 | try { 38 | let reviewId = node.getAttribute("data-review-id"); 39 | review.id = reviewId; 40 | } catch (_) { 41 | review.id = null; 42 | } 43 | 44 | try { 45 | let author = node.getElementsByClassName("display-name-link")[0]; 46 | 47 | review.author = entityDecoder(author.textContent.trim(), { 48 | level: "html5", 49 | }); 50 | 51 | review.authorUrl = 52 | "https://www.imdb.com" + 53 | author.getElementsByTagName("a")[0].getAttribute("href"); 54 | } catch (_) { 55 | if (!review.author) review.author = "Anonymous"; 56 | if (!review.authorUrl) review.authorUrl = null; 57 | } 58 | 59 | try { 60 | review.user_api_path = 61 | "/user/" + review.authorUrl.match(/\/user\/(.*)\//)[1]; 62 | } catch (error) { 63 | review.user_api_path = null; 64 | } 65 | 66 | try { 67 | let reviewDate = node.getElementsByClassName("review-date")[0]; 68 | reviewDate = reviewDate.textContent.trim(); 69 | review.date = new Date(reviewDate).toISOString(); 70 | } catch (error) { 71 | review.date = null; 72 | } 73 | 74 | try { 75 | let stars = 76 | node.getElementsByClassName("ipl-ratings-bar")[0].textContent; 77 | let match = stars.match(/\d+/g); 78 | review.stars = parseInt(match[0]); 79 | } catch (_) { 80 | review.stars = 0; 81 | } 82 | 83 | try { 84 | let heading = node.getElementsByClassName("title")[0]; 85 | review.heading = entityDecoder(heading.textContent.trim(), { 86 | level: "html5", 87 | }); 88 | } catch (_) { 89 | review.heading = null; 90 | } 91 | 92 | try { 93 | let content = node.getElementsByClassName("text")[0]; 94 | review.content = entityDecoder(content.textContent.trim(), { 95 | level: "html5", 96 | }); 97 | } catch (_) { 98 | review.content = null; 99 | } 100 | 101 | try { 102 | let helpfulNess = node 103 | .getElementsByClassName("actions")[0] 104 | .textContent.trim(); 105 | 106 | // text will be like this '223 out of 280 found this helpful' 107 | let match = helpfulNess.match(/\d+/g); 108 | 109 | review.helpfulNess = { 110 | votes: parseInt(match[1]), 111 | votedAsHelpful: parseInt(match[0]), 112 | votedAsHelpfulPercentage: 113 | Math.round((parseInt(match[0]) / parseInt(match[1])) * 100) || 0, 114 | }; 115 | } catch (_) { 116 | review.helpfulNess = { 117 | votes: 0, 118 | votedAsHelpful: 0, 119 | votedAsHelpfulPercentage: 0, 120 | }; 121 | } 122 | 123 | review.reviewLink = `https://www.imdb.com/review/${review.id}`; 124 | 125 | reviews.push(review); 126 | } catch (__) {} 127 | }); 128 | 129 | let next = null; 130 | 131 | try { 132 | let morePage = dom.getElementsByClassName("load-more-data")[0]; 133 | next = morePage.getAttribute("data-key"); 134 | next = `/reviews/${id}?option=${option.name}&sortOrder=${sortOrder}&nextKey=${next}`; 135 | } catch (_) {} 136 | 137 | let result = { 138 | id, 139 | imdb: `https://www.imdb.com/title/${id}`, 140 | option: option.name, 141 | sortOrder, 142 | availableOptions: optionsMapper.map((option) => option.name), 143 | availableSortOrders: ["asc", "desc"], 144 | reviews, 145 | next_api_path: next, 146 | }; 147 | 148 | return c.json(result); 149 | } catch (error) { 150 | c.status(500); 151 | return c.json({ 152 | message: error.message, 153 | }); 154 | } 155 | }); 156 | 157 | export default reviews; 158 | 159 | const optionsMapper = [ 160 | { 161 | key: "helpfulnessScore", 162 | name: "helpfulness", 163 | }, 164 | { 165 | key: "submissionDate", 166 | name: "date", 167 | }, 168 | { 169 | key: "totalVotes", 170 | name: "votes", 171 | }, 172 | { 173 | key: "userRating", 174 | name: "rating", 175 | }, 176 | ]; 177 | -------------------------------------------------------------------------------- /src/routes/search.js: -------------------------------------------------------------------------------- 1 | import { Hono } from "hono"; 2 | import { apiRequestJson } from "../helpers/apiRequestRawHtml"; 3 | 4 | const search = new Hono(); 5 | 6 | search.get("/", async (c) => { 7 | try { 8 | let query = c.req.query("query"); 9 | if (!query) throw new Error("Query param is required"); 10 | 11 | let data = await apiRequestJson( 12 | `https://v3.sg.media-imdb.com/suggestion/x/${query}.json?includeVideos=0` 13 | ); 14 | 15 | let response = { 16 | query: query, 17 | }; 18 | 19 | let titles = []; 20 | 21 | data.d.forEach((node) => { 22 | try { 23 | if (!node.qid) return; 24 | if (!["movie", "tvSeries", "tvMovie"].includes(node.qid)) return; 25 | 26 | let imageObj = { 27 | image: null, 28 | image_large: null, 29 | }; 30 | 31 | if (node.i) { 32 | imageObj.image_large = node.i.imageUrl; 33 | 34 | try { 35 | let width = Math.floor((396 * node.i.width) / node.i.height); 36 | 37 | imageObj.image = node.i.imageUrl.replace( 38 | /[.]_.*_[.]/, 39 | `._V1_UY396_CR6,0,${width},396_AL_.` 40 | ); 41 | } catch (_) { 42 | imageObj.image = imageObj.image_large; 43 | } 44 | } 45 | 46 | titles.push({ 47 | id: node.id, 48 | title: node.l, 49 | year: node.y, 50 | type: node.qid, 51 | ...imageObj, 52 | api_path: `/title/${node.id}`, 53 | imdb: `https://www.imdb.com/title/${node.id}`, 54 | }); 55 | } catch (_) { 56 | console.log(_); 57 | } 58 | }); 59 | 60 | response.message = `Found ${titles.length} titles`; 61 | response.results = titles; 62 | 63 | return c.json(response); 64 | } catch (error) { 65 | c.status(500); 66 | let errorMessage = error.message; 67 | if (error.message.includes("Too many")) 68 | errorMessage = 69 | "Too many requests error from IMDB, please try again later"; 70 | 71 | return c.json({ 72 | query: null, 73 | results: [], 74 | message: errorMessage, 75 | }); 76 | } 77 | }); 78 | 79 | export default search; 80 | -------------------------------------------------------------------------------- /src/routes/title.js: -------------------------------------------------------------------------------- 1 | import { Hono } from "hono"; 2 | import { getSeason } from "../helpers/seriesFetcher"; 3 | import getTitle from "../helpers/getTitle"; 4 | 5 | const title = new Hono(); 6 | 7 | title.get("/:id", async (c) => { 8 | const id = c.req.param("id"); 9 | 10 | try { 11 | const result = await getTitle(id); 12 | 13 | return c.json(result); 14 | } catch (error) { 15 | c.status(500); 16 | return c.json({ 17 | message: error.message, 18 | }); 19 | } 20 | }); 21 | 22 | title.get("/:id/season/:seasonId", async (c) => { 23 | const id = c.req.param("id"); 24 | const seasonId = c.req.param("seasonId"); 25 | 26 | try { 27 | const result = await getSeason({ id, seasonId }); 28 | 29 | const response = Object.assign( 30 | { 31 | id, 32 | title_api_path: `/title/${id}`, 33 | imdb: `https://www.imdb.com/title/${id}/episodes?season=${seasonId}`, 34 | season_id: seasonId, 35 | }, 36 | result 37 | ); 38 | 39 | return c.json(response); 40 | } catch (error) { 41 | c.status(500); 42 | return c.json({ 43 | message: error.message, 44 | }); 45 | } 46 | }); 47 | 48 | export default title; 49 | 50 | function getNode(dom, tag, id) { 51 | return dom 52 | .getElementsByTagName(tag) 53 | .find((e) => e.attributes.find((e) => e.value === id)); 54 | } 55 | -------------------------------------------------------------------------------- /src/routes/user/index.js: -------------------------------------------------------------------------------- 1 | import { Hono } from "hono"; 2 | import userInfo from "./info"; 3 | import userRating from "./rating"; 4 | const userRoutes = new Hono(); 5 | 6 | userRoutes.get("/:id", userInfo); 7 | userRoutes.get("/:id/ratings", userRating); 8 | 9 | export default userRoutes; 10 | -------------------------------------------------------------------------------- /src/routes/user/info.js: -------------------------------------------------------------------------------- 1 | import DomParser from "dom-parser"; 2 | 3 | export default async function userInfo(c) { 4 | let errorStatus = 500; 5 | 6 | try { 7 | const userId = c.req.param("id"); 8 | const response = await fetch(`https://www.imdb.com/user/${userId}`, { 9 | headers: { 10 | "User-Agent": 11 | "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36", 12 | accept: "text/html", 13 | "accept-language": "en-US", 14 | }, 15 | }); 16 | 17 | if (!response.ok) { 18 | errorStatus = response.status; 19 | throw new Error( 20 | errorStatus === 404 21 | ? "Seems like user is not exixts." 22 | : "Error fetching user info." 23 | ); 24 | } 25 | 26 | const rawHtml = await response.text(); 27 | const parser = new DomParser(); 28 | const dom = parser.parseFromString(rawHtml); 29 | 30 | let data = {}; 31 | 32 | try { 33 | const name = rawHtml.match(/

(.*)<\/h1>/)[1]; 34 | data.name = name || null; 35 | } catch (__) { 36 | data.name = null; 37 | } 38 | 39 | try { 40 | const created = rawHtml.match( 41 | /
IMDb member since (.*)<\/div>/ 42 | )[1]; 43 | data.member_since = created || null; 44 | } catch (__) { 45 | data.created = null; 46 | } 47 | 48 | try { 49 | let image = dom.getElementById("avatar"); 50 | const imageSrc = image.getAttribute("src"); 51 | 52 | if (imageSrc) { 53 | data.image = imageSrc.replace("._V1_SY100_SX100_", ""); 54 | } else { 55 | data.image = null; 56 | } 57 | } catch (__) { 58 | data.image = null; 59 | } 60 | 61 | try { 62 | let badges = dom.getElementsByClassName("badges")[0]; 63 | let mappedBadges = badges.childNodes 64 | .map((node) => { 65 | try { 66 | return { 67 | name: node.getElementsByClassName("name")[0].textContent, 68 | value: node.getElementsByClassName("value")[0].textContent, 69 | }; 70 | } catch (__) {} 71 | }) 72 | .filter(Boolean); 73 | 74 | data.badges = mappedBadges; 75 | } catch (_) { 76 | data.badges = []; 77 | } 78 | 79 | const result = Object.assign( 80 | { 81 | id: userId, 82 | imdb: `https://www.imdb.com/user/${userId}`, 83 | ratings_api_path: `/user/${userId}/ratings`, 84 | }, 85 | data 86 | ); 87 | 88 | return c.json(result); 89 | } catch (error) { 90 | c.status(errorStatus); 91 | return c.json({ 92 | message: error.message, 93 | }); 94 | } 95 | } 96 | -------------------------------------------------------------------------------- /src/routes/user/rating.js: -------------------------------------------------------------------------------- 1 | import DomParser from "dom-parser"; 2 | import qs from "qs"; 3 | import apiRequestRawHtml from "../../helpers/apiRequestRawHtml"; 4 | 5 | const SORT_OPTIONS = { 6 | most_recent: "date_added,desc", 7 | oldest: "date_added,asc", 8 | top_rated: "your_rating,desc", 9 | worst_rated: "your_rating,asc", 10 | }; 11 | 12 | export default async function userRating(c) { 13 | let errorStatus = 500; 14 | 15 | try { 16 | const userId = c.req.param("id"); 17 | 18 | const sort = 19 | SORT_OPTIONS[c.req.query("sort") || ""] || Object.values(SORT_OPTIONS)[0]; 20 | const ratingFilter = c.req.query("ratingFilter") || null; 21 | 22 | const query = qs.stringify({ 23 | sort, 24 | ratingFilter: ratingFilter || undefined, 25 | }); 26 | 27 | const constructedUrl = `https://www.imdb.com/user/${userId}/ratings?${query}`; 28 | 29 | const response = await fetch(constructedUrl, { 30 | headers: { 31 | "User-Agent": 32 | "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36", 33 | accept: "text/html", 34 | "accept-language": "en-US", 35 | }, 36 | }); 37 | 38 | if (!response.ok) { 39 | errorStatus = response.status; 40 | throw new Error( 41 | errorStatus === 404 42 | ? "Seems like user rating is not exixts." 43 | : "Error fetching user rating." 44 | ); 45 | } 46 | 47 | const rawHtml = await response.text(); 48 | const parser = new DomParser(); 49 | const dom = parser.parseFromString(rawHtml); 50 | 51 | let total_ratings = 0; 52 | let total_filtered_ratings = 0; 53 | let all_ratings = []; 54 | 55 | try { 56 | const totalRatings = rawHtml.match(/span> [(]of (\d+)[)] titles/)[1]; 57 | total_ratings = parseInt(totalRatings); 58 | } catch (_) {} 59 | 60 | try { 61 | const totalFilteredRatings = dom.getElementById( 62 | "lister-header-current-size" 63 | ).textContent; 64 | total_filtered_ratings = parseInt(totalFilteredRatings); 65 | } catch (_) {} 66 | 67 | try { 68 | const listNode = dom.getElementById("ratings-container"); 69 | const lists = listNode 70 | .getElementsByClassName("mode-detail") 71 | .slice(0, 100); // limit to 100 72 | 73 | for (const node of lists) { 74 | const parsed = parseContent(node); 75 | if (parsed) all_ratings.push(parsed); 76 | } 77 | } catch (_) {} 78 | 79 | const allReviews = await parseReviews(userId); 80 | 81 | // merge reviews 82 | all_ratings = all_ratings.map((rating) => { 83 | let review = allReviews.find((review) => review.title_id === rating.id); 84 | if (review) delete review.title_id; 85 | 86 | return { 87 | ...rating, 88 | review: review || null, 89 | }; 90 | }); 91 | 92 | const result = { 93 | id: userId, 94 | imdb: constructedUrl, 95 | user_api_path: `/user/${userId}`, 96 | allSortOptions: Object.keys(SORT_OPTIONS), 97 | allRatingFilters: ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"], 98 | total_user_ratings: total_ratings, 99 | total_filtered_ratings, 100 | ratings: all_ratings, 101 | }; 102 | 103 | return c.json(result); 104 | } catch (error) { 105 | c.status(errorStatus); 106 | return c.json({ 107 | message: error.message, 108 | }); 109 | } 110 | } 111 | 112 | async function parseReviews(userId) { 113 | try { 114 | let data = []; 115 | const rawHtml = await apiRequestRawHtml( 116 | `https://www.imdb.com/user/${userId}/reviews` 117 | ); 118 | 119 | const parser = new DomParser(); 120 | const dom = parser.parseFromString(rawHtml); 121 | 122 | const allLists = dom.getElementsByClassName("lister-item"); 123 | 124 | for (const node of allLists) { 125 | try { 126 | const id = node.getAttribute("data-review-id"); 127 | const imdb = node.getAttribute("data-vote-url"); 128 | const titleId = imdb.match(/title\/(.*)\/review/)[1]; 129 | const reviewContent = 130 | node.getElementsByClassName("show-more__control")[0]; 131 | const reviewTitle = node.getElementsByClassName("title")[0]; 132 | 133 | let review_date = node 134 | .getElementsByClassName("review-date")[0] 135 | .textContent.trim(); 136 | review_date = new Date(review_date).toISOString(); 137 | 138 | data.push({ 139 | title_id: titleId, 140 | 141 | id, 142 | date: review_date, 143 | heading: reviewTitle.textContent.trim(), 144 | content: reviewContent.textContent.trim(), 145 | reviewLink: `https://www.imdb.com/review/${id}`, 146 | }); 147 | } catch (_) { 148 | console.error(`Reviews error:`, _); 149 | } 150 | } 151 | 152 | return data; 153 | } catch (error) { 154 | console.error(`Reviews error:`, error); 155 | return []; 156 | } 157 | } 158 | 159 | function parseContent(node) { 160 | try { 161 | let object = {}; 162 | 163 | const nodeInnerHtml = node.innerHTML; 164 | const titleNode = node.getElementsByClassName("lister-item-header")[0]; 165 | const title = titleNode.getElementsByTagName("a")[0]; 166 | const titleUrl = title.getAttribute("href"); 167 | const titleId = titleUrl.match(/title\/(.*)\//)[1]; 168 | 169 | object.id = titleId; 170 | object.imdb = `https://www.imdb.com/title/${titleId}`; 171 | object.api_path = `/title/${titleId}`; 172 | object.review_api_path = `/reviews/${titleId}`; 173 | object.title = title.textContent.trim(); 174 | 175 | const userRatingNode = node.getElementsByClassName( 176 | "ipl-rating-star--other-user" 177 | )[0]; 178 | const userRating = userRatingNode.getElementsByClassName( 179 | "ipl-rating-star__rating" 180 | )[0]; 181 | 182 | object.userRating = parseInt(userRating.textContent.trim()); 183 | 184 | try { 185 | const ratedOn = nodeInnerHtml.match(/>Rated on (.*)<[\/]p>/)[1]; 186 | object.date = new Date(ratedOn).toISOString(); 187 | } catch (error) { 188 | object.date = null; 189 | } 190 | 191 | try { 192 | const plot = nodeInnerHtml.match(/

\s(.*)<[\/]p>/)[1]; 193 | object.plot = plot.trim(); 194 | } catch (error) { 195 | object.plot = null; 196 | } 197 | 198 | try { 199 | const image = node.getElementsByClassName("loadlate")[0]; 200 | object.image = image.getAttribute("loadlate"); 201 | object.image_large = object.image.replace(/._.*_/, ""); 202 | } catch (error) { 203 | object.image = null; 204 | object.image_large = null; 205 | } 206 | 207 | try { 208 | const genre = node.getElementsByClassName("genre")[0].textContent; 209 | object.genre = genre.split(",").map((g) => g.trim()); 210 | } catch (_) { 211 | object.genre = ["Error"]; 212 | } 213 | 214 | try { 215 | const allUserRating = node.getElementsByClassName( 216 | "ipl-rating-star__rating" 217 | )[0]; 218 | 219 | let votes = -1; 220 | try { 221 | votes = node.getElementsByName("nv")[0].getAttribute("data-value"); 222 | } catch (__) {} 223 | 224 | object.rating = { 225 | star: parseFloat(allUserRating.textContent.trim()), 226 | count: parseInt(votes), 227 | }; 228 | } catch (error) { 229 | object.rating = { 230 | count: -1, 231 | star: -1, 232 | }; 233 | } 234 | 235 | try { 236 | object.contentRating = 237 | node.getElementsByClassName("certificate")[0].textContent; 238 | } catch (_) { 239 | object.contentRating = null; 240 | } 241 | 242 | try { 243 | object.runtime = node.getElementsByClassName("runtime")[0].textContent; 244 | object.runtimeSeconds = parseRuntimeIntoSeconds(object.runtime); 245 | } catch (_) { 246 | object.runtime = null; 247 | object.runtimeSeconds = -1; 248 | } 249 | 250 | return object; 251 | } catch (error) { 252 | console.log(error); 253 | return null; 254 | } 255 | } 256 | 257 | function parseRuntimeIntoSeconds(runtime) { 258 | try { 259 | let seconds = 0; 260 | 261 | const hrMatch = runtime.match(/(\d+)\shr/); 262 | if (hrMatch) { 263 | seconds += parseInt(hrMatch[1]) * 60 * 60; 264 | } 265 | 266 | const minMatch = runtime.match(/(\d+)\smin/); 267 | if (minMatch) { 268 | seconds += parseInt(minMatch[1]) * 60; 269 | } 270 | 271 | return Math.floor(seconds); 272 | } catch (error) { 273 | return -1; 274 | } 275 | } 276 | -------------------------------------------------------------------------------- /tests/search.test.js: -------------------------------------------------------------------------------- 1 | const axios = require("axios"); 2 | 3 | test("test search route", async () => { 4 | let data = await axios.get( 5 | "http://localhost:8787/search?query=Rise Roar Revolt" 6 | ); 7 | 8 | expect(data.status).toBe(200); 9 | expect(data.data.results.length).not.toBe(0); 10 | expect(typeof data.data.message).toBe("undefined"); 11 | }); 12 | -------------------------------------------------------------------------------- /tests/title.test.js: -------------------------------------------------------------------------------- 1 | const axios = require("axios"); 2 | 3 | test("test title route movie", async () => { 4 | let data = await axios.get("http://localhost:8787/title/tt8178634"); 5 | 6 | expect(data.status).toBe(200); 7 | expect(data.data.contentType).toBe("Movie"); 8 | expect(Array.isArray(data.data.rating.count)).not.toBe(0); 9 | expect(Array.isArray(data.data.rating.star)).not.toBe(0); 10 | expect(Array.isArray(data.data.year)).not.toBe(null); 11 | expect(Array.isArray(data.data.runtime)).not.toBe(null); 12 | expect(Array.isArray(data.data.actors)).toBe(true); 13 | expect(Array.isArray(data.data.directors)).toBe(true); 14 | }); 15 | 16 | test("test title route tvseries", async () => { 17 | let data = await axios.get("http://127.0.0.1:8787/title/tt5491994"); 18 | 19 | expect(data.status).toBe(200); 20 | expect(data.data.contentType).toBe("TVSeries"); 21 | expect(Array.isArray(data.data.rating.count)).not.toBe(0); 22 | expect(Array.isArray(data.data.rating.star)).not.toBe(0); 23 | expect(Array.isArray(data.data.actors)).toBe(true); 24 | expect(Array.isArray(data.data.directors)).toBe(true); 25 | expect(Array.isArray(data.data.seasons)).toBe(true); 26 | expect(data.data.seasons.length > 0).toBe(true); 27 | }); 28 | -------------------------------------------------------------------------------- /wrangler.toml: -------------------------------------------------------------------------------- 1 | name = "imdb-api" 2 | 3 | workers_dev = true 4 | compatibility_date = "2023-02-28" 5 | --------------------------------------------------------------------------------