├── .releaserc.json ├── .DS_Store ├── .gitattributes ├── example ├── small.jpg ├── small.mp4 ├── env.js ├── index.cjs └── index.html ├── src ├── album │ ├── index.ts │ ├── createAlbum.test.ts │ ├── getAlbum.ts │ ├── createAlbum.ts │ └── getAlbum.test.ts ├── account │ ├── index.ts │ ├── getAccount.ts │ ├── getAlbumsIds.ts │ ├── getAlbums.ts │ ├── getAccount.test.ts │ ├── getAlbums.test.ts │ └── getAlbumsIds.test.ts ├── gallery │ ├── index.ts │ ├── getSubredditGallery.ts │ ├── searchGallery.test.ts │ ├── getSubredditGallery.test.ts │ ├── getGallery.test.ts │ ├── searchGallery.ts │ └── getGallery.ts ├── mocks │ ├── server.ts │ ├── handlers │ │ ├── gallery.ts │ │ ├── credits.ts │ │ ├── image.ts │ │ ├── account.ts │ │ ├── albums.ts │ │ ├── album.ts │ │ ├── index.ts │ │ ├── upload.ts │ │ └── authorize.ts │ └── vitest.setup.ts ├── index.umd.ts ├── image │ ├── index.ts │ ├── getImage.ts │ ├── deleteImage.ts │ ├── favoriteImage.ts │ ├── deleteImage.test.ts │ ├── favoriteImage.test.ts │ ├── getImage.test.ts │ ├── updateImage.ts │ ├── upload.ts │ ├── updateImage.test.ts │ └── upload.test.ts ├── index.ts ├── getAuthorizationHeader.test.ts ├── common │ ├── endpoints.ts │ ├── utils.ts │ └── types.ts ├── getAuthorizationHeader.ts └── client.ts ├── .gitignore ├── .prettierrc.json ├── .prettierignore ├── .npmignore ├── vitest.config.ts ├── eslint.config.js ├── vite.umd.config.ts ├── tsconfig.json ├── vite.config.ts ├── .github ├── ISSUE_TEMPLATE │ ├── feature_request.md │ └── bug_report.md └── workflows │ ├── test.yaml │ └── release.yaml ├── CONTRIBUTING.md ├── package.json ├── CODE_OF_CONDUCT.md ├── README.md └── LICENSE.md /.releaserc.json: -------------------------------------------------------------------------------- 1 | { 2 | "branches": [{ "name": "main" }] 3 | } 4 | -------------------------------------------------------------------------------- /.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/KenEucker/imgur/HEAD/.DS_Store -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | *.ts linguist-detectable=true 2 | *.* linguist-detectable=false -------------------------------------------------------------------------------- /example/small.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/KenEucker/imgur/HEAD/example/small.jpg -------------------------------------------------------------------------------- /example/small.mp4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/KenEucker/imgur/HEAD/example/small.mp4 -------------------------------------------------------------------------------- /src/album/index.ts: -------------------------------------------------------------------------------- 1 | export * from './createAlbum'; 2 | export * from './getAlbum'; 3 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | src/coverage 3 | *.code-workspace 4 | lib 5 | dist 6 | .DS_Store 7 | .env 8 | coverage -------------------------------------------------------------------------------- /src/account/index.ts: -------------------------------------------------------------------------------- 1 | export * from './getAccount'; 2 | export * from './getAlbums'; 3 | export * from './getAlbumsIds'; 4 | -------------------------------------------------------------------------------- /.prettierrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "trailingComma": "es5", 3 | "tabWidth": 2, 4 | "semi": true, 5 | "singleQuote": true 6 | } 7 | -------------------------------------------------------------------------------- /.prettierignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | lib/ 3 | package-lock.json 4 | .github 5 | src/coverage/ 6 | example 7 | imgur.js 8 | imgur.node.js 9 | -------------------------------------------------------------------------------- /src/gallery/index.ts: -------------------------------------------------------------------------------- 1 | export * from './getGallery'; 2 | export * from './getSubredditGallery'; 3 | export * from './searchGallery'; 4 | -------------------------------------------------------------------------------- /example/env.js: -------------------------------------------------------------------------------- 1 | const env = { 2 | "CLIENT_ID": "YOUR-CLIENT-ID", 3 | "ACCESS_TOKEN": "YOUR-ACCESS-TOKEN", 4 | "ALBUM": "YOUR-ALBUM" 5 | } -------------------------------------------------------------------------------- /src/mocks/server.ts: -------------------------------------------------------------------------------- 1 | import { setupServer } from 'msw/node'; 2 | import { handlers } from './handlers'; 3 | 4 | export const server = setupServer(...handlers); 5 | -------------------------------------------------------------------------------- /src/index.umd.ts: -------------------------------------------------------------------------------- 1 | import { ImgurClient } from './client'; 2 | export type { ImgurCredentials, ImgurApiResponse } from './client'; 3 | export default ImgurClient; 4 | -------------------------------------------------------------------------------- /src/image/index.ts: -------------------------------------------------------------------------------- 1 | export * from './deleteImage'; 2 | export * from './favoriteImage'; 3 | export * from './getImage'; 4 | export * from './updateImage'; 5 | export * from './upload'; 6 | -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | .prettierignore 2 | .eslintrc.js 3 | .prettierrc.json 4 | .releaserc.json 5 | .github 6 | 7 | tsconfig.json 8 | 9 | src 10 | 11 | CODE_OF_CONDUCT.md 12 | CONTRIBUTING.md 13 | 14 | *.code-workspace 15 | -------------------------------------------------------------------------------- /src/album/createAlbum.test.ts: -------------------------------------------------------------------------------- 1 | import { describe, test, expect } from 'vitest'; 2 | 3 | describe('test imgur album creation', () => { 4 | test('no tests ready because issues', async () => { 5 | expect(true).toBe(true); 6 | }); 7 | }); 8 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | import { ImgurClient } from './client'; 2 | export { ImgurClient }; 3 | export type { ImgurCredentials, ImgurApiResponse } from './client'; 4 | export { getAuthorizationHeader } from './getAuthorizationHeader'; 5 | export default ImgurClient; 6 | -------------------------------------------------------------------------------- /vitest.config.ts: -------------------------------------------------------------------------------- 1 | import { defineConfig } from 'vitest/config'; 2 | 3 | export default defineConfig({ 4 | test: { 5 | environment: 'happy-dom', // or "jsdom" 6 | setupFiles: ['./src/mocks/vitest.setup.ts'], 7 | globals: true, 8 | }, 9 | }); 10 | -------------------------------------------------------------------------------- /eslint.config.js: -------------------------------------------------------------------------------- 1 | import { defineConfig } from 'eslint/config'; 2 | 3 | export default defineConfig([ 4 | { 5 | files: ['src/**/*.js'], 6 | ignores: ['**/*.config.js', '!**/eslint.config.js'], 7 | rules: { 8 | semi: 'error', 9 | }, 10 | 11 | ignores: [ 12 | 'lib/', 13 | 'src/coverage/', 14 | 'dist/', 15 | 'vite.config.ts', 16 | 'example', 17 | 'imgur.js', 18 | 'imgur.mjs', 19 | ], 20 | }, 21 | ]); 22 | -------------------------------------------------------------------------------- /vite.umd.config.ts: -------------------------------------------------------------------------------- 1 | import { defineConfig } from 'vite'; 2 | import path from 'path'; 3 | 4 | export default defineConfig({ 5 | build: { 6 | lib: { 7 | entry: path.resolve(__dirname, 'src/index.umd.ts'), 8 | name: 'ImgurClient', 9 | formats: ['umd'], 10 | fileName: () => 'imgur.umd.js', 11 | }, 12 | outDir: 'dist', 13 | emptyOutDir: false, // do not wipe out the esm/cjs files 14 | rollupOptions: { 15 | output: { 16 | exports: 'default', 17 | }, 18 | }, 19 | }, 20 | }); 21 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "include": ["src/**/*"], 3 | "exclude": ["src/coverage/", "src/mocks/", "src/**/*.test.ts"], 4 | "compilerOptions": { 5 | "experimentalDecorators": true, 6 | "moduleResolution": "node", 7 | "module": "es6", 8 | "target": "es6", 9 | "typeRoots": ["@types", "./node_modules/@types"], 10 | "rootDir": "./src", 11 | "outDir": "lib", 12 | "esModuleInterop": true, 13 | "importHelpers": true, 14 | "resolveJsonModule": true, 15 | "allowSyntheticDefaultImports": true, 16 | "declaration": true 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/album/getAlbum.ts: -------------------------------------------------------------------------------- 1 | import { ImgurClient } from '../client'; 2 | import { ALBUM_ENDPOINT } from '../common/endpoints'; 3 | import { ImgurApiResponse, AlbumData } from '../common/types'; 4 | import { getImgurApiResponseFromResponse } from '../common/utils'; 5 | 6 | export async function getAlbum( 7 | client: ImgurClient, 8 | albumHash: string 9 | ): Promise> { 10 | const url = `${ALBUM_ENDPOINT}/${albumHash}`; 11 | return getImgurApiResponseFromResponse( 12 | await client.request({ url }).catch((e) => e.response) 13 | ) as ImgurApiResponse; 14 | } 15 | -------------------------------------------------------------------------------- /src/image/getImage.ts: -------------------------------------------------------------------------------- 1 | import { ImgurClient } from '../client'; 2 | import { IMAGE_ENDPOINT } from '../common/endpoints'; 3 | import { ImgurApiResponse, ImageData } from '../common/types'; 4 | import { getImgurApiResponseFromResponse } from '../common/utils'; 5 | 6 | export async function getImage( 7 | client: ImgurClient, 8 | imageHash: string 9 | ): Promise> { 10 | const url = `${IMAGE_ENDPOINT}/${imageHash}`; 11 | return getImgurApiResponseFromResponse( 12 | await client.request({ url }).catch((e) => e.response) 13 | ) as ImgurApiResponse; 14 | } 15 | -------------------------------------------------------------------------------- /src/image/deleteImage.ts: -------------------------------------------------------------------------------- 1 | import { ImgurClient } from '../client'; 2 | import { IMAGE_ENDPOINT } from '../common/endpoints'; 3 | import { ImgurApiResponse } from '../common/types'; 4 | import { getImgurApiResponseFromResponse } from '../common/utils'; 5 | 6 | export async function deleteImage( 7 | client: ImgurClient, 8 | imageHash: string 9 | ): Promise> { 10 | const url = `${IMAGE_ENDPOINT}/${imageHash}`; 11 | return getImgurApiResponseFromResponse( 12 | await client.request({ url, method: 'DELETE' }).catch((e) => e.response) 13 | ) as ImgurApiResponse; 14 | } 15 | -------------------------------------------------------------------------------- /src/account/getAccount.ts: -------------------------------------------------------------------------------- 1 | import { ImgurClient } from '../client'; 2 | import { ACCOUNT_ENDPOINT } from '../common/endpoints'; 3 | import { ImgurApiResponse, AccountData } from '../common/types'; 4 | import { getImgurApiResponseFromResponse } from '../common/utils'; 5 | 6 | export async function getAccount( 7 | client: ImgurClient, 8 | account: string 9 | ): Promise> { 10 | const url = `${ACCOUNT_ENDPOINT}/${account}`; 11 | return getImgurApiResponseFromResponse( 12 | await client.plainRequest({ url }).catch((e) => e.response) 13 | ) as ImgurApiResponse; 14 | } 15 | -------------------------------------------------------------------------------- /src/image/favoriteImage.ts: -------------------------------------------------------------------------------- 1 | import { ImgurClient } from '../client'; 2 | import { IMAGE_ENDPOINT } from '../common/endpoints'; 3 | import { ImgurApiResponse } from '../common/types'; 4 | import { getImgurApiResponseFromResponse } from '../common/utils'; 5 | 6 | export async function favoriteImage( 7 | client: ImgurClient, 8 | imageHash: string 9 | ): Promise> { 10 | const url = `${IMAGE_ENDPOINT}/${imageHash}/favorite`; 11 | return getImgurApiResponseFromResponse( 12 | await client.request({ url, method: 'POST' }).catch((e) => e.response) 13 | ) as ImgurApiResponse<'favorited'>; 14 | } 15 | -------------------------------------------------------------------------------- /src/account/getAlbumsIds.ts: -------------------------------------------------------------------------------- 1 | import { ImgurClient } from '../client'; 2 | import { ACCOUNT_ENDPOINT } from '../common/endpoints'; 3 | import { ImgurApiResponse } from '../common/types'; 4 | import { getImgurApiResponseFromResponse } from '../common/utils'; 5 | 6 | export async function getAlbumsIds( 7 | client: ImgurClient, 8 | account: string, 9 | page?: number 10 | ): Promise> { 11 | const url = `${ACCOUNT_ENDPOINT}/${account}/albums/ids/${page ?? ''}`; 12 | return getImgurApiResponseFromResponse( 13 | await client.request({ url }).catch((e) => e.response) 14 | ) as ImgurApiResponse; 15 | } 16 | -------------------------------------------------------------------------------- /src/account/getAlbums.ts: -------------------------------------------------------------------------------- 1 | import { ImgurClient } from '../client'; 2 | import { ACCOUNT_ENDPOINT } from '../common/endpoints'; 3 | import { AlbumData, ImgurApiResponse } from '../common/types'; 4 | import { getImgurApiResponseFromResponse } from '../common/utils'; 5 | 6 | export async function getAlbums( 7 | client: ImgurClient, 8 | account: string, 9 | page?: number 10 | ): Promise> { 11 | const url = `${ACCOUNT_ENDPOINT}/${account}/albums/${page ?? ''}`; 12 | return getImgurApiResponseFromResponse( 13 | await client.request({ url }).catch((e) => e.response) 14 | ) as ImgurApiResponse; 15 | } 16 | -------------------------------------------------------------------------------- /src/image/deleteImage.test.ts: -------------------------------------------------------------------------------- 1 | import { ImgurClient } from '../client'; 2 | import { deleteImage } from './deleteImage'; 3 | import { test, expect } from 'vitest'; 4 | 5 | test('delete works successfully', async () => { 6 | const accessToken = 'abc123'; 7 | const client = new ImgurClient({ accessToken }); 8 | const response = await deleteImage(client, 'CEddrgP'); 9 | expect(response).toMatchInlineSnapshot(` 10 | { 11 | "data": true, 12 | "headers": { 13 | "content-length": "41", 14 | "content-type": "application/json", 15 | }, 16 | "status": 200, 17 | "success": true, 18 | } 19 | `); 20 | }); 21 | -------------------------------------------------------------------------------- /src/image/favoriteImage.test.ts: -------------------------------------------------------------------------------- 1 | import { ImgurClient } from '../client'; 2 | import { favoriteImage } from './favoriteImage'; 3 | import { test, expect } from 'vitest'; 4 | 5 | test('favorite works successfully', async () => { 6 | const accessToken = 'abc123'; 7 | const client = new ImgurClient({ accessToken }); 8 | const response = await favoriteImage(client, 'CEddrgP'); 9 | expect(response).toMatchInlineSnapshot(` 10 | { 11 | "data": "favorited", 12 | "headers": { 13 | "content-length": "48", 14 | "content-type": "application/json", 15 | }, 16 | "status": 200, 17 | "success": true, 18 | } 19 | `); 20 | }); 21 | -------------------------------------------------------------------------------- /vite.config.ts: -------------------------------------------------------------------------------- 1 | import { defineConfig } from 'vite'; 2 | import dts from 'vite-plugin-dts'; 3 | import path from 'path'; 4 | 5 | export default defineConfig({ 6 | plugins: [dts()], 7 | build: { 8 | target: 'node16', 9 | lib: { 10 | entry: path.resolve(__dirname, 'src/index.ts'), 11 | formats: ['es', 'cjs'], 12 | }, 13 | outDir: 'dist', 14 | emptyOutDir: true, 15 | rollupOptions: { 16 | external: ['axios', 'form-data', 'events'], 17 | output: { 18 | exports: 'named', 19 | globals: { 20 | // list any external deps you expect the consumer to provide 21 | }, 22 | }, 23 | }, 24 | }, 25 | }); 26 | -------------------------------------------------------------------------------- /src/mocks/handlers/gallery.ts: -------------------------------------------------------------------------------- 1 | import { HttpResponse } from 'msw'; 2 | 3 | export const getHandler = () => { 4 | const response = { 5 | data: [ 6 | { 7 | id: 'ans7sd', 8 | title: 'gallery-title', 9 | description: 'gallery-description', 10 | link: 'https://imgur.com/a/abc123', 11 | images: [ 12 | { 13 | id: '4yMKKLTz', 14 | title: null, 15 | description: null, 16 | link: 'https://i.imgur.com/4yMKKLTz.jpg', 17 | }, 18 | ], 19 | }, 20 | ], 21 | success: true, 22 | status: 200, 23 | }; 24 | 25 | return HttpResponse.json(response, { status: 200 }); 26 | }; 27 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this project 4 | title: '' 5 | labels: Feature Request 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Is your feature request related to a problem? Please describe.** 11 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] 12 | 13 | **Describe the solution you'd like** 14 | A clear and concise description of what you want to happen. 15 | 16 | **Describe alternatives you've considered** 17 | A clear and concise description of any alternative solutions or features you've considered. 18 | 19 | **Additional context** 20 | Add any other context or screenshots about the feature request here. 21 | -------------------------------------------------------------------------------- /src/getAuthorizationHeader.test.ts: -------------------------------------------------------------------------------- 1 | import { ImgurClient } from './client'; 2 | import { getAuthorizationHeader } from './getAuthorizationHeader'; 3 | 4 | test('returns provided access code in bearer header', async () => { 5 | const accessToken = 'abc123'; 6 | const client = new ImgurClient({ accessToken }); 7 | const authorizationHeader = await getAuthorizationHeader(client); 8 | expect(authorizationHeader).toBe(`Bearer ${accessToken}`); 9 | }); 10 | 11 | test('returns provided client id in client id header', async () => { 12 | const clientId = 'abc123'; 13 | const client = new ImgurClient({ clientId }); 14 | const authorizationHeader = await getAuthorizationHeader(client); 15 | expect(authorizationHeader).toBe(`Client-ID ${clientId}`); 16 | }); 17 | -------------------------------------------------------------------------------- /src/image/getImage.test.ts: -------------------------------------------------------------------------------- 1 | import { ImgurClient } from '../client'; 2 | import { getImage } from './getImage'; 3 | import { test, expect } from 'vitest'; 4 | 5 | test('returns an image response', async () => { 6 | const accessToken = 'abc123'; 7 | const client = new ImgurClient({ accessToken }); 8 | const response = await getImage(client, 'CEddrgP'); 9 | expect(response).toMatchInlineSnapshot(` 10 | { 11 | "data": { 12 | "description": "image-description", 13 | "id": "CEddrgP", 14 | "title": "image-title", 15 | }, 16 | "headers": { 17 | "content-length": "109", 18 | "content-type": "application/json", 19 | }, 20 | "status": 200, 21 | "success": true, 22 | } 23 | `); 24 | }); 25 | -------------------------------------------------------------------------------- /src/mocks/vitest.setup.ts: -------------------------------------------------------------------------------- 1 | import { beforeAll, beforeEach, afterAll, afterEach } from 'vitest'; 2 | import { server } from './server'; 3 | // import mockfs from 'mock-fs'; 4 | 5 | // Establish API mocking before all tests. 6 | beforeAll(() => server.listen()); 7 | 8 | beforeEach(() => { 9 | // mockfs({ 10 | // 'fixtures/1x1.png': Buffer.from([8, 6, 7, 5, 3, 0, 9]), 11 | // 'fixtures/small.mp4': Buffer.from([9, 0, 3, 5, 7, 6, 8, 1, 2, 3, 4, 5]), 12 | // }); 13 | }); 14 | 15 | // Reset any request handlers that we may add during the tests, 16 | // so they don't affect other tests. 17 | afterEach(() => { 18 | // mockfs.restore(); 19 | server.resetHandlers(); 20 | }); 21 | 22 | // Clean up after the tests are finished. 23 | afterAll(() => server.close()); 24 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | title: "[BUG] " 5 | labels: Bug 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Describe the bug** 11 | A clear and concise description of what the bug is. 12 | 13 | **To Reproduce** 14 | Steps to reproduce the behavior: 15 | 1. Call method '...' 16 | 2. Await promise '....' 17 | 3. See error 18 | 19 | **Expected behavior** 20 | A clear and concise description of what you expected to happen. 21 | 22 | **Screenshots** 23 | If applicable, add screenshots to help explain your problem. 24 | 25 | **Environment (please complete the following information):** 26 | - Library version [e.g. 1.0.0]: 27 | - OS [e.g. macOS]: 28 | - NodeJS version [e.g.14.16.0]: 29 | 30 | **Additional context** 31 | Add any other context about the problem here. 32 | -------------------------------------------------------------------------------- /src/mocks/handlers/credits.ts: -------------------------------------------------------------------------------- 1 | import { HttpResponse } from 'msw'; 2 | 3 | const AuthenticationRequiredResponse = { 4 | data: { 5 | error: 'Authentication required', 6 | request: '/3/credits', 7 | method: 'GET', 8 | }, 9 | success: false, 10 | status: 401, 11 | }; 12 | 13 | const SuccessResponse = { 14 | data: { 15 | UserLimit: 500, 16 | UserRemaining: 500, 17 | UserReset: 1615614380, 18 | ClientLimit: 12500, 19 | ClientRemaining: 12500, 20 | }, 21 | success: true, 22 | status: 200, 23 | }; 24 | 25 | export const getHandler = (request) => { 26 | const authHeader = request.headers.get('authorization'); 27 | 28 | if (!authHeader) { 29 | return HttpResponse.json(AuthenticationRequiredResponse, { status: 401 }); 30 | } 31 | 32 | return HttpResponse.json(SuccessResponse, { status: 200 }); 33 | }; 34 | -------------------------------------------------------------------------------- /.github/workflows/test.yaml: -------------------------------------------------------------------------------- 1 | name: Tests 2 | 3 | on: 4 | pull_request: 5 | branches: ['*'] 6 | 7 | jobs: 8 | test: 9 | name: Test on node ${{ matrix.node-version }} 10 | runs-on: ubuntu-latest 11 | 12 | strategy: 13 | matrix: 14 | node-version: [20.x] 15 | 16 | steps: 17 | - name: Checkout Repository 18 | uses: actions/checkout@v3 19 | with: 20 | fetch-depth: 0 21 | - name: Use Node.js ${{ matrix.node-version }} 22 | uses: actions/setup-node@v3 23 | with: 24 | node-version: ${{ matrix.node-version }} 25 | - name: Install dependencies 26 | run: npm ci 27 | - name: Run Linters 28 | run: npm run lint:release 29 | - name: Build 30 | run: npm run build --if-present 31 | - name: Run tests 32 | run: npm run test:ci 33 | -------------------------------------------------------------------------------- /src/common/endpoints.ts: -------------------------------------------------------------------------------- 1 | export const IMGUR_API_PREFIX = 'https://api.imgur.com'; 2 | 3 | export const API_VERSION = '3'; 4 | 5 | /// DEPRECATED: this endpoint is only used for 'code' or 'pin' type authentication, 6 | /// which are both deprecated by Imgur (see: ) 7 | export const AUTHORIZE_ENDPOINT = 'oauth2/authorize'; 8 | 9 | export const TOKEN_ENDPOINT = 'oauth2/token'; 10 | 11 | export const ACCOUNT_ENDPOINT = `${API_VERSION}/account`; 12 | 13 | export const ALBUM_ENDPOINT = `${API_VERSION}/album`; 14 | 15 | export const IMAGE_ENDPOINT = `${API_VERSION}/image`; 16 | 17 | export const UPLOAD_ENDPOINT = `${API_VERSION}/upload`; 18 | 19 | export const GALLERY_ENDPOINT = `${API_VERSION}/gallery`; 20 | 21 | export const SUBREDDIT_GALLERY_ENDPOINT = `${API_VERSION}/gallery/r`; 22 | 23 | export const SEARCH_GALLERY_ENDPOINT = `${API_VERSION}/gallery/search`; 24 | -------------------------------------------------------------------------------- /src/album/createAlbum.ts: -------------------------------------------------------------------------------- 1 | import { ImgurClient } from '../client'; 2 | import { ALBUM_ENDPOINT } from '../common/endpoints'; 3 | import { ImgurApiResponse, AlbumData } from '../common/types'; 4 | import { createForm, getImgurApiResponseFromResponse } from '../common/utils'; 5 | 6 | export async function createAlbum( 7 | client: ImgurClient, 8 | title?: string, 9 | description?: string 10 | ): Promise> { 11 | const form = createForm({ title, description }); 12 | const response = await client 13 | .request({ 14 | url: ALBUM_ENDPOINT, 15 | headers: form.getHeaders(), 16 | method: 'POST', 17 | data: form, 18 | }) 19 | .catch((e) => e.response); 20 | 21 | if (response.data?.success && response.data?.data) { 22 | response.data.data.title = title; 23 | response.data.data.description = description; 24 | } 25 | return getImgurApiResponseFromResponse( 26 | response 27 | ) as ImgurApiResponse; 28 | } 29 | -------------------------------------------------------------------------------- /src/mocks/handlers/image.ts: -------------------------------------------------------------------------------- 1 | import { HttpResponse } from 'msw'; 2 | 3 | const SuccessResponse = { 4 | data: true, 5 | success: true, 6 | status: 200, 7 | }; 8 | 9 | const FavoriteSuccessResponse = { 10 | data: 'favorited', 11 | success: true, 12 | status: 200, 13 | }; 14 | 15 | export const getHandler = (request) => { 16 | const { id } = request.params; 17 | 18 | const response = { 19 | data: { 20 | id, 21 | title: 'image-title', 22 | description: 'image-description', 23 | }, 24 | success: true, 25 | status: 200, 26 | }; 27 | 28 | return HttpResponse.json(response, { status: 200 }); 29 | }; 30 | 31 | export const postHandler = () => { 32 | return HttpResponse.json(SuccessResponse, { status: 200 }); 33 | }; 34 | 35 | export const deleteHandler = () => { 36 | return HttpResponse.json(SuccessResponse, { status: 200 }); 37 | }; 38 | 39 | export const postFavoriteHandler = () => { 40 | return HttpResponse.json(FavoriteSuccessResponse, { status: 200 }); 41 | }; 42 | -------------------------------------------------------------------------------- /.github/workflows/release.yaml: -------------------------------------------------------------------------------- 1 | name: Release 2 | 3 | on: 4 | push: 5 | branches: 6 | - main 7 | 8 | jobs: 9 | release: 10 | name: Release 11 | runs-on: ubuntu-latest 12 | 13 | steps: 14 | - name: Checkout Repository 15 | uses: actions/checkout@v3 16 | with: 17 | fetch-depth: 0 18 | - name: Setup Node 19 | uses: actions/setup-node@v3 20 | with: 21 | node-version: 20 22 | - name: Reconfigure git to use HTTP authentication 23 | run: > 24 | git config --global url."https://github.com/".insteadOf 25 | ssh://git@github.com/ 26 | - name: Install dependencies 27 | run: npm ci 28 | - name: Run linters 29 | run: npm run lint:release 30 | - name: Build 31 | run: npm run build 32 | - name: Run tests 33 | run: npm run test:ci 34 | - name: Release 35 | env: 36 | GH_TOKEN: ${{ secrets.GH_TOKEN }} 37 | NPM_TOKEN: ${{ secrets.NPM_TOKEN }} 38 | run: npx semantic-release 39 | -------------------------------------------------------------------------------- /example/index.cjs: -------------------------------------------------------------------------------- 1 | const { ImgurClient, getAuthorizationHeader } = require('../'); 2 | const { createReadStream } = require('fs'); 3 | const { join } = require('path'); 4 | require('dotenv').config(); 5 | 6 | const album = process.env.ALBUM; 7 | const imgur = new ImgurClient({ 8 | username: process.env.USERNAME, 9 | password: process.env.PASSWORD, 10 | refreshToken: process.env.REFRESH_TOKEN, 11 | accessToken: process.env.ACCESS_TOKEN, 12 | clientSecret: process.env.CLIENT_SECRET, 13 | clientId: process.env.CLIENT_ID, 14 | rapidApiKey: process.env.RAPID_API_KEY, 15 | }); 16 | 17 | const run = async (client) => { 18 | 19 | await getAuthorizationHeader(client).then(console.log) 20 | console.log(client.credentials) 21 | 22 | const imageStream = createReadStream(join(__dirname, 'small.jpg')); 23 | const videoStream = createReadStream(join(__dirname, 'small.mp4')); 24 | 25 | await client.createAlbum('test').then(console.log) 26 | 27 | // await client.upload({ album, image: imageStream, type: 'stream' }).then(console.log); 28 | // await client.upload({ album, image: videoStream, type: 'stream' }).then(console.log); 29 | 30 | } 31 | 32 | run(imgur) 33 | -------------------------------------------------------------------------------- /src/mocks/handlers/account.ts: -------------------------------------------------------------------------------- 1 | import { HttpResponse } from 'msw'; 2 | 3 | const AuthenticationRequiredResponse = { 4 | data: { 5 | error: 'Authentication required', 6 | request: '/3/account', 7 | method: 'POST', 8 | }, 9 | success: false, 10 | status: 401, 11 | }; 12 | 13 | const SuccessResponse = { 14 | data: { 15 | id: 'XtMnA', 16 | title: 'Meme album', 17 | description: 'Dank memes', 18 | image_count: 22, 19 | images: [ 20 | { 21 | id: '2dAns', 22 | title: null, 23 | description: null, 24 | datetime: 1316635799, 25 | type: 'image/gif', 26 | link: 'https://i.imgur.com/2dAns.gif', 27 | }, 28 | { 29 | id: 'snAd2', 30 | title: null, 31 | description: null, 32 | datetime: 1316635800, 33 | type: 'image/jpeg', 34 | link: 'https://i.imgur.com/2dAns.jpg', 35 | }, 36 | ], 37 | }, 38 | success: true, 39 | status: 200, 40 | }; 41 | 42 | export const getHandler = (request) => { 43 | const authHeader = request.headers.get('authorization'); 44 | 45 | if (!authHeader) { 46 | return HttpResponse.json(AuthenticationRequiredResponse, { status: 401 }); 47 | } 48 | 49 | return HttpResponse.json(SuccessResponse, { status: 200 }); 50 | }; 51 | -------------------------------------------------------------------------------- /src/mocks/handlers/albums.ts: -------------------------------------------------------------------------------- 1 | import { HttpResponse } from 'msw'; 2 | 3 | const AuthenticationRequiredResponse = { 4 | data: { 5 | error: 'Authentication required', 6 | request: '/3/account/albums', 7 | method: 'POST', 8 | }, 9 | success: false, 10 | status: 401, 11 | }; 12 | 13 | const SuccessResponse = { 14 | data: { 15 | id: 'XtMnA', 16 | title: 'Meme album', 17 | description: 'Dank memes', 18 | image_count: 22, 19 | images: [ 20 | { 21 | id: '2dAns', 22 | title: null, 23 | description: null, 24 | datetime: 1316635799, 25 | type: 'image/gif', 26 | link: 'https://i.imgur.com/2dAns.gif', 27 | }, 28 | { 29 | id: 'snAd2', 30 | title: null, 31 | description: null, 32 | datetime: 1316635800, 33 | type: 'image/jpeg', 34 | link: 'https://i.imgur.com/2dAns.jpg', 35 | }, 36 | ], 37 | }, 38 | success: true, 39 | status: 200, 40 | }; 41 | 42 | export const getHandler = (request) => { 43 | const authHeader = request.headers.get('authorization'); 44 | 45 | if (!authHeader) { 46 | return HttpResponse.json(AuthenticationRequiredResponse, { status: 401 }); 47 | } 48 | 49 | return HttpResponse.json(SuccessResponse, { status: 200 }); 50 | }; 51 | -------------------------------------------------------------------------------- /src/mocks/handlers/album.ts: -------------------------------------------------------------------------------- 1 | import { HttpResponse } from 'msw'; 2 | 3 | const AuthenticationRequiredResponse = { 4 | data: { 5 | error: 'Authentication required', 6 | request: '/3/album', 7 | method: 'POST', 8 | }, 9 | success: false, 10 | status: 401, 11 | }; 12 | 13 | const SuccessResponse = { 14 | data: { 15 | id: 'XtMnA', 16 | title: 'Meme album', 17 | description: 'Dank memes', 18 | image_count: 22, 19 | images: [ 20 | { 21 | id: '2dAns', 22 | title: null, 23 | description: null, 24 | datetime: 1316635799, 25 | type: 'image/gif', 26 | link: 'https://i.imgur.com/2dAns.gif', 27 | }, 28 | { 29 | id: 'snAd2', 30 | title: null, 31 | description: null, 32 | datetime: 1316635800, 33 | type: 'image/jpeg', 34 | link: 'https://i.imgur.com/2dAns.jpg', 35 | }, 36 | ], 37 | }, 38 | success: true, 39 | status: 200, 40 | }; 41 | 42 | export const getHandler = (request) => { 43 | /// TODO: fix this doubled up error 44 | const authHeader = request.request.headers.get('authorization'); 45 | 46 | if (!authHeader) { 47 | return HttpResponse.json(AuthenticationRequiredResponse, { status: 401 }); 48 | } 49 | 50 | return HttpResponse.json(SuccessResponse, { status: 200 }); 51 | }; 52 | -------------------------------------------------------------------------------- /src/album/getAlbum.test.ts: -------------------------------------------------------------------------------- 1 | import { ImgurClient } from '../client'; 2 | import { getAlbum } from './getAlbum'; 3 | import { test, expect } from 'vitest'; 4 | 5 | test('returns an album response', async () => { 6 | const accessToken = 'abc123'; 7 | const client = new ImgurClient({ accessToken }); 8 | const response = await getAlbum(client, 'XtMnA'); 9 | expect(response).toMatchInlineSnapshot(` 10 | { 11 | "data": { 12 | "description": "Dank memes", 13 | "id": "XtMnA", 14 | "image_count": 22, 15 | "images": [ 16 | { 17 | "datetime": 1316635799, 18 | "description": null, 19 | "id": "2dAns", 20 | "link": "https://i.imgur.com/2dAns.gif", 21 | "title": null, 22 | "type": "image/gif", 23 | }, 24 | { 25 | "datetime": 1316635800, 26 | "description": null, 27 | "id": "snAd2", 28 | "link": "https://i.imgur.com/2dAns.jpg", 29 | "title": null, 30 | "type": "image/jpeg", 31 | }, 32 | ], 33 | "title": "Meme album", 34 | }, 35 | "headers": { 36 | "content-length": "382", 37 | "content-type": "application/json", 38 | }, 39 | "status": 200, 40 | "success": true, 41 | } 42 | `); 43 | }); 44 | -------------------------------------------------------------------------------- /src/account/getAccount.test.ts: -------------------------------------------------------------------------------- 1 | test.todo('returns an account response'); 2 | // import { ImgurClient } from '../client'; 3 | // import { getAccount } from './getAccount'; 4 | // import { test, expect } from 'vitest' 5 | 6 | // test('returns an account response', async () => { 7 | // const accessToken = 'abc123'; 8 | // const client = new ImgurClient({ accessToken }); 9 | // const response = await getAccount(client, 'XtMnA'); 10 | // expect(response).toMatchInlineSnapshot(` 11 | // { 12 | // "data": { 13 | // "description": "Dank memes", 14 | // "id": "XtMnA", 15 | // "image_count": 22, 16 | // "images": [ 17 | // { 18 | // "datetime": 1316635799, 19 | // "description": null, 20 | // "id": "2dAns", 21 | // "link": "https://i.imgur.com/2dAns.gif", 22 | // "title": null, 23 | // "type": "image/gif", 24 | // }, 25 | // { 26 | // "datetime": 1316635800, 27 | // "description": null, 28 | // "id": "snAd2", 29 | // "link": "https://i.imgur.com/2dAns.jpg", 30 | // "title": null, 31 | // "type": "image/jpeg", 32 | // }, 33 | // ], 34 | // "title": "Meme album", 35 | // }, 36 | // "status": 200, 37 | // "success": true, 38 | // } 39 | // `); 40 | // }); 41 | -------------------------------------------------------------------------------- /src/account/getAlbums.test.ts: -------------------------------------------------------------------------------- 1 | import { test } from 'vitest'; 2 | 3 | test.todo('returns an array of albums response'); 4 | // import { ImgurClient } from '../client'; 5 | // import { getAlbums } from './getAlbums'; 6 | 7 | // test('returns an array of albums response', async () => { 8 | // const accessToken = 'abc123'; 9 | // const client = new ImgurClient({ accessToken }); 10 | // const response = await getAlbums(client, 'node-imgur'); 11 | // expect(response).toMatchInlineSnapshot(` 12 | // { 13 | // "data": { 14 | // "description": "Dank memes", 15 | // "id": "XtMnA", 16 | // "image_count": 22, 17 | // "images": [ 18 | // { 19 | // "datetime": 1316635799, 20 | // "description": null, 21 | // "id": "2dAns", 22 | // "link": "https://i.imgur.com/2dAns.gif", 23 | // "title": null, 24 | // "type": "image/gif", 25 | // }, 26 | // { 27 | // "datetime": 1316635800, 28 | // "description": null, 29 | // "id": "snAd2", 30 | // "link": "https://i.imgur.com/2dAns.jpg", 31 | // "title": null, 32 | // "type": "image/jpeg", 33 | // }, 34 | // ], 35 | // "title": "Meme album", 36 | // }, 37 | // "status": 200, 38 | // "success": true, 39 | // } 40 | // `); 41 | // }); 42 | -------------------------------------------------------------------------------- /src/image/updateImage.ts: -------------------------------------------------------------------------------- 1 | import { ImgurClient } from '../client'; 2 | import { IMAGE_ENDPOINT } from '../common/endpoints'; 3 | import { createForm, getImgurApiResponseFromResponse } from '../common/utils'; 4 | import { Payload, ImgurApiResponse } from '../common/types'; 5 | 6 | export interface UpdateImagePayload 7 | extends Pick { 8 | imageHash: string; 9 | } 10 | 11 | function isValidUpdatePayload(p: UpdateImagePayload) { 12 | return typeof p.title === 'string' || typeof p.description === 'string'; 13 | } 14 | 15 | export async function updateImage( 16 | client: ImgurClient, 17 | payload: UpdateImagePayload 18 | ): Promise> { 19 | if (!isValidUpdatePayload(payload)) { 20 | throw new Error('Update requires a title and/or description'); 21 | } 22 | 23 | const url = `${IMAGE_ENDPOINT}/${payload.imageHash}`; 24 | const form = createForm(payload); 25 | /* eslint no-async-promise-executor: 0 */ 26 | return new Promise(async (resolve) => { 27 | return resolve( 28 | getImgurApiResponseFromResponse( 29 | await client 30 | .request({ 31 | url, 32 | method: 'POST', 33 | data: form, 34 | headers: form.getHeaders(), 35 | }) 36 | .catch((e) => e.response) 37 | ) as ImgurApiResponse 38 | ); 39 | }) as Promise>; 40 | } 41 | -------------------------------------------------------------------------------- /src/account/getAlbumsIds.test.ts: -------------------------------------------------------------------------------- 1 | import { test } from 'vitest'; 2 | 3 | test.todo('returns an array of album ids response'); 4 | // import { ImgurClient } from '../client'; 5 | // import { getAlbumsIds } from './getAlbumsIds'; 6 | 7 | // test('returns an array of album ids response', async () => { 8 | // const accessToken = 'abc123'; 9 | // const client = new ImgurClient({ accessToken }); 10 | // const response = await getAlbumsIds(client, 'node-imgur'); 11 | // expect(response).toMatchInlineSnapshot(` 12 | // { 13 | // "data": { 14 | // "description": "Dank memes", 15 | // "id": "XtMnA", 16 | // "image_count": 22, 17 | // "images": [ 18 | // { 19 | // "datetime": 1316635799, 20 | // "description": null, 21 | // "id": "2dAns", 22 | // "link": "https://i.imgur.com/2dAns.gif", 23 | // "title": null, 24 | // "type": "image/gif", 25 | // }, 26 | // { 27 | // "datetime": 1316635800, 28 | // "description": null, 29 | // "id": "snAd2", 30 | // "link": "https://i.imgur.com/2dAns.jpg", 31 | // "title": null, 32 | // "type": "image/jpeg", 33 | // }, 34 | // ], 35 | // "title": "Meme album", 36 | // }, 37 | // "status": 200, 38 | // "success": true, 39 | // } 40 | // `); 41 | // }); 42 | -------------------------------------------------------------------------------- /src/mocks/handlers/index.ts: -------------------------------------------------------------------------------- 1 | import { http } from 'msw'; 2 | 3 | import * as upload from './upload'; 4 | import * as authorize from './authorize'; 5 | import * as image from './image'; 6 | import * as gallery from './gallery'; 7 | import * as credits from './credits'; 8 | import * as albums from './albums'; 9 | import * as album from './album'; 10 | import * as account from './account'; 11 | 12 | export const handlers = [ 13 | // authorize 14 | http.get('https://api.imgur.com/oauth2/authorize', authorize.getHandler), 15 | http.post('https://api.imgur.com/oauth2/authorize', authorize.postHandler), 16 | 17 | // album 18 | http.get('https://api.imgur.com/3/album/:id', album.getHandler), 19 | 20 | // upload 21 | http.post('https://api.imgur.com/3/upload', upload.postHandler), 22 | 23 | // gallery 24 | http.get('https://api.imgur.com/3/gallery/*', gallery.getHandler), 25 | 26 | // image 27 | http.get('https://api.imgur.com/3/image/:id', image.getHandler), 28 | http.post('https://api.imgur.com/3/image/:id', image.postHandler), 29 | http.post( 30 | 'https://api.imgur.com/3/image/:id/favorite', 31 | image.postFavoriteHandler 32 | ), 33 | http.delete('https://api.imgur.com/3/image/:id', image.deleteHandler), 34 | 35 | // credits 36 | http.get('https://api.imgur.com/3/credits', credits.getHandler), 37 | 38 | // account 39 | http.get('https://api.imgur.com/3/account/:username', account.getHandler), 40 | http.get('https://api.imgur.com/3/account/albums/:page', albums.getHandler), 41 | ]; 42 | -------------------------------------------------------------------------------- /src/image/upload.ts: -------------------------------------------------------------------------------- 1 | import { ImgurClient } from '../client'; 2 | import { 3 | createForm, 4 | getImgurApiResponseFromResponse, 5 | hasPathOrName, 6 | } from '../common/utils'; 7 | import { Payload, ImgurApiResponse, ImageData } from '../common/types'; 8 | import { UPLOAD_ENDPOINT, IMAGE_ENDPOINT } from '../common/endpoints'; 9 | 10 | export async function upload( 11 | client: ImgurClient, 12 | payload: Payload 13 | ): Promise> { 14 | const form = createForm(payload); 15 | const image = payload.image; 16 | const filename = 17 | typeof image === 'string' 18 | ? image 19 | : hasPathOrName(image) 20 | ? (image.path ?? image.name) 21 | : ''; 22 | const isVideo = 23 | payload.type === 'stream' && 24 | filename && 25 | (filename.indexOf('.mp4') !== -1 || filename.indexOf('.avi') !== -1); 26 | const url = isVideo ? UPLOAD_ENDPOINT : IMAGE_ENDPOINT; 27 | 28 | /* eslint no-async-promise-executor: 0 */ 29 | return new Promise(async (resolve) => { 30 | return resolve( 31 | getImgurApiResponseFromResponse( 32 | await client 33 | .request({ 34 | url, 35 | method: 'POST', 36 | data: form, 37 | headers: form.getHeaders(), 38 | onUploadProgress: (progressEvent) => { 39 | client.emit('uploadProgress', { ...progressEvent }); 40 | }, 41 | }) 42 | .catch((e) => e.response) 43 | ) as ImgurApiResponse 44 | ); 45 | }) as Promise>; 46 | } 47 | -------------------------------------------------------------------------------- /src/getAuthorizationHeader.ts: -------------------------------------------------------------------------------- 1 | import { 2 | isAccessToken, 3 | isRefreshToken, 4 | isClientId, 5 | ImgurTokenResponse, 6 | Credentials, 7 | } from './common/types'; 8 | import { ImgurClient } from './client'; 9 | import { IMGUR_API_PREFIX, TOKEN_ENDPOINT } from './common/endpoints'; 10 | 11 | export async function getAuthorizationHeader( 12 | client: ImgurClient 13 | ): Promise { 14 | if (isAccessToken(client.credentials)) { 15 | return `Bearer ${client.credentials.accessToken}`; 16 | } 17 | 18 | const { clientId, clientSecret, refreshToken } = client.credentials; 19 | 20 | if (isRefreshToken(client.credentials)) { 21 | const options: Record = { 22 | url: TOKEN_ENDPOINT, 23 | baseURL: IMGUR_API_PREFIX, 24 | method: 'POST', 25 | data: { 26 | client_id: clientId, 27 | client_secret: clientSecret, 28 | refresh_token: refreshToken, 29 | grant_type: 'refresh_token', 30 | }, 31 | }; 32 | const response = await client.plainRequest(options); 33 | 34 | if (response.status === 200 && response.data) { 35 | const { access_token: accessToken, refresh_token: refreshToken } = 36 | response.data as ImgurTokenResponse; 37 | 38 | (client.credentials as Credentials).accessToken = accessToken; 39 | (client.credentials as Credentials).refreshToken = refreshToken; 40 | 41 | return `Bearer ${accessToken}`; 42 | } 43 | } 44 | 45 | if (isClientId(client.credentials)) { 46 | return `Client-ID ${clientId}`; 47 | } 48 | 49 | return null; 50 | } 51 | -------------------------------------------------------------------------------- /src/image/updateImage.test.ts: -------------------------------------------------------------------------------- 1 | import { ImgurClient } from '../client'; 2 | import { updateImage } from './updateImage'; 3 | import { test, expect } from 'vitest'; 4 | 5 | test('update one image with all props', async () => { 6 | const accessToken = 'abc123'; 7 | const client = new ImgurClient({ accessToken }); 8 | const response = await updateImage(client, { 9 | imageHash: 'abc123', 10 | title: 'new title', 11 | description: 'description', 12 | }); 13 | expect(response).toMatchInlineSnapshot(` 14 | { 15 | "data": true, 16 | "headers": { 17 | "content-length": "41", 18 | "content-type": "application/json", 19 | }, 20 | "status": 200, 21 | "success": true, 22 | } 23 | `); 24 | }); 25 | 26 | test('update one image with title only', async () => { 27 | const accessToken = 'abc123'; 28 | const client = new ImgurClient({ accessToken }); 29 | const response = await updateImage(client, { 30 | imageHash: 'abc123', 31 | title: 'new title', 32 | }); 33 | expect(response).toMatchInlineSnapshot(` 34 | { 35 | "data": true, 36 | "headers": { 37 | "content-length": "41", 38 | "content-type": "application/json", 39 | }, 40 | "status": 200, 41 | "success": true, 42 | } 43 | `); 44 | }); 45 | 46 | test('update one image without title or description', async () => { 47 | const accessToken = 'abc123'; 48 | const client = new ImgurClient({ accessToken }); 49 | const response = updateImage(client, { 50 | imageHash: 'abc123', 51 | }); 52 | await expect(response).rejects.toThrowErrorMatchingInlineSnapshot( 53 | `[Error: Update requires a title and/or description]` 54 | ); 55 | }); 56 | -------------------------------------------------------------------------------- /src/gallery/getSubredditGallery.ts: -------------------------------------------------------------------------------- 1 | import { ImgurClient } from '../client'; 2 | import { 3 | SUBREDDIT_GALLERY_ENDPOINT, 4 | IMGUR_API_PREFIX, 5 | } from '../common/endpoints'; 6 | import { ImgurApiResponse, GalleryData } from '../common/types'; 7 | import { URL } from 'whatwg-url'; 8 | import { getImgurApiResponseFromResponse } from '../common/utils'; 9 | 10 | export type TimeOptions = { 11 | subreddit: string; 12 | sort?: 'time'; 13 | page?: number; 14 | }; 15 | 16 | export type TopOptions = Omit & { 17 | sort?: 'top'; 18 | window?: 'day' | 'week' | 'month' | 'year' | 'all'; 19 | }; 20 | 21 | export type SubredditGalleryOptions = TimeOptions | TopOptions; 22 | 23 | export function constructSubredditGalleryUrl( 24 | options: SubredditGalleryOptions 25 | ): URL { 26 | let uri = `${options.subreddit}`; 27 | 28 | if (options.sort) { 29 | uri += `/${options.sort}`; 30 | } 31 | 32 | if (options.sort === 'top' && options.window) { 33 | uri += `/${options.window}`; 34 | } 35 | 36 | if (options.page) { 37 | uri += `/${options.page}`; 38 | } 39 | 40 | const url = new URL( 41 | `${IMGUR_API_PREFIX}/${SUBREDDIT_GALLERY_ENDPOINT}/${uri}` 42 | ); 43 | 44 | return url; 45 | } 46 | 47 | export async function getSubredditGallery( 48 | client: ImgurClient, 49 | options: SubredditGalleryOptions 50 | ): Promise> { 51 | const { pathname } = constructSubredditGalleryUrl(options); 52 | // since we're using prefixUrl with got, we have to remove the starting slash or it'll throw 53 | const finalPathname = pathname.slice(1); 54 | 55 | return getImgurApiResponseFromResponse( 56 | await client.request({ url: finalPathname }).catch((e) => e.response) 57 | ) as ImgurApiResponse; 58 | } 59 | -------------------------------------------------------------------------------- /src/mocks/handlers/upload.ts: -------------------------------------------------------------------------------- 1 | import { HttpResponse } from 'msw'; 2 | 3 | const BadRequestErrorResponse = { 4 | status: 400, 5 | success: false, 6 | data: { 7 | error: 'Bad Request', 8 | request: '/3/upload', 9 | method: 'POST', 10 | }, 11 | }; 12 | 13 | type CreateResponseOptions = { 14 | id?: string; 15 | type?: string | null; 16 | title?: string | null; 17 | description?: string | null; 18 | }; 19 | 20 | function createResponse({ 21 | id = 'JK9ybyj', 22 | type = null, 23 | title = null, 24 | description = null, 25 | }: CreateResponseOptions) { 26 | return { 27 | data: { 28 | id, 29 | deletehash: Array.from(id).reverse().join(''), 30 | title, 31 | description, 32 | link: `https://i.imgur.com/${id}.${type === 'video' ? 'mp4' : 'jpg'}`, 33 | }, 34 | success: true, 35 | status: 200, 36 | }; 37 | } 38 | 39 | export const postHandler = async (request) => { 40 | const formData = await request.formData(); 41 | 42 | const image = formData.get('image')?.valueOf() ?? null; 43 | const stream = formData.get('stream')?.valueOf() ?? null; 44 | const base64 = formData.get('base64')?.valueOf() ?? null; 45 | const type = formData.get('type')?.valueOf() ?? null; 46 | const title = formData.get('title')?.valueOf() ?? null; 47 | const description = formData.get('description')?.valueOf() ?? null; 48 | 49 | if (image === null && stream === null && base64 === null) { 50 | return HttpResponse.json(BadRequestErrorResponse, { status: 400 }); 51 | } 52 | 53 | if (type !== null && !['stream', 'url', 'base64'].includes(type as string)) { 54 | return HttpResponse.json(BadRequestErrorResponse, { status: 400 }); 55 | } 56 | 57 | return HttpResponse.json( 58 | createResponse({ 59 | title: title as string, 60 | description: description as string, 61 | }), 62 | { status: 200 } 63 | ); 64 | }; 65 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # How to Contribute 2 | 3 | Thanks for taking the time to contribute! 4 | 5 | - [Code of Conduct][code of conduct] 6 | 7 | ## Testing 8 | 9 | We are using the [Vitest][vitest] framework for testing. Imgur API mocking is configured via [msw][msw]. This makes it simple to mock API responses. Simply add a new handler for an endpoint to `mocks/handlers.js` and that's it. These mocks are automatically configured to work for all new and existing tests. 10 | 11 | Here's an example that mocks a response when making a `POST` request to `https://api.imgur.com/3/image`: 12 | 13 | ```js 14 | const handlers = [ 15 | rest.post('https://api.imgur.com/3/image', (_req, res, ctx) => { 16 | const response = { 17 | data: { 18 | id: 'JK9ybyj', 19 | deletehash: 'j83zimv4VtDA0Xp', 20 | link: 'https://i.imgur.com/JK9ybyj.jpg', 21 | }, 22 | success: true, 23 | status: 200, 24 | }; 25 | return res(ctx.json(response)); 26 | }), 27 | ]; 28 | ``` 29 | 30 | ## Submitting Changes 31 | 32 | We use [commitizen][commitizen] to enforce [conventional commits][conventional commits]. This enables us to automate both semantic versioning and npm releases. 33 | 34 | Install the `commitizen` command line tool: 35 | 36 | ```bash 37 | npm install -g commitizen 38 | ``` 39 | 40 | Now simply use `git cz` or just `cz` instead of `git commit` when committing. 41 | 42 | If you prefer not to install the `commitizen` command globally, alternatively you can use `npm run commit` instead of `git commit`. 43 | 44 | ## Coding Conventions 45 | 46 | - Prettier is ran and applied automatically as part of a precommit hook, so you don't have to worry about semicolons or trailing commas 47 | 48 | [vitest]: https://vitest.dev/ 49 | [msw]: https://mswjs.io/ 50 | [commitizen]: https://github.com/commitizen/cz-cli 51 | [conventional commits]: https://www.conventionalcommits.org/ 52 | [code of conduct]: CODE_OF_CONDUCT.md 53 | -------------------------------------------------------------------------------- /src/gallery/searchGallery.test.ts: -------------------------------------------------------------------------------- 1 | import { ImgurClient } from '../client'; 2 | import { searchGallery, constructSearchGalleryUrl } from './searchGallery'; 3 | import { test, expect } from 'vitest'; 4 | 5 | test('constructGalleryUrl', () => { 6 | expect( 7 | constructSearchGalleryUrl({ 8 | q: 'cats', 9 | }).href 10 | ).toMatchInlineSnapshot(`"https://api.imgur.com/3/gallery/search?q=cats"`); 11 | 12 | expect( 13 | constructSearchGalleryUrl({ query: 'dogs', sort: 'time' }).href 14 | ).toMatchInlineSnapshot( 15 | `"https://api.imgur.com/3/gallery/search/time?q=dogs"` 16 | ); 17 | 18 | expect( 19 | constructSearchGalleryUrl({ 20 | q: 'cats subreddit:awwa ext:gif', 21 | sort: 'top', 22 | window: 'month', 23 | }).href 24 | ).toMatchInlineSnapshot( 25 | `"https://api.imgur.com/3/gallery/search/top/month?q=cats+subreddit%3Aawwa+ext%3Agif"` 26 | ); 27 | 28 | const { href } = constructSearchGalleryUrl({ 29 | query: 'wallstreetbets', 30 | q_all: 'nintendo switch', 31 | q_not: 'mario', 32 | q_type: 'anigif', 33 | q_size_px: 'lrg', 34 | }); 35 | expect(href).toMatchInlineSnapshot( 36 | `"https://api.imgur.com/3/gallery/search?q_all=nintendo+switch&q_not=mario&q_type=anigif&q_size_px=lrg"` 37 | ); 38 | }); 39 | 40 | test('returns an gallery response', async () => { 41 | const accessToken = 'abc123'; 42 | const client = new ImgurClient({ accessToken }); 43 | const response = await searchGallery(client, { 44 | query: 'wallstreetbets', 45 | }); 46 | expect(response).toMatchInlineSnapshot(` 47 | { 48 | "data": [ 49 | { 50 | "description": "gallery-description", 51 | "id": "ans7sd", 52 | "images": [ 53 | { 54 | "description": null, 55 | "id": "4yMKKLTz", 56 | "link": "https://i.imgur.com/4yMKKLTz.jpg", 57 | "title": null, 58 | }, 59 | ], 60 | "link": "https://imgur.com/a/abc123", 61 | "title": "gallery-title", 62 | }, 63 | ], 64 | "headers": { 65 | "content-length": "253", 66 | "content-type": "application/json", 67 | }, 68 | "status": 200, 69 | "success": true, 70 | } 71 | `); 72 | }); 73 | -------------------------------------------------------------------------------- /src/gallery/getSubredditGallery.test.ts: -------------------------------------------------------------------------------- 1 | import { ImgurClient } from '../client'; 2 | import { 3 | getSubredditGallery, 4 | constructSubredditGalleryUrl, 5 | } from './getSubredditGallery'; 6 | import { test, expect } from 'vitest'; 7 | 8 | test('constructGalleryUrl', () => { 9 | expect( 10 | constructSubredditGalleryUrl({ 11 | subreddit: 'wallstreetbets', 12 | }).pathname 13 | ).toMatchInlineSnapshot(`"/3/gallery/r/wallstreetbets"`); 14 | 15 | expect( 16 | constructSubredditGalleryUrl({ subreddit: 'wallstreetbets', sort: 'time' }) 17 | .pathname 18 | ).toMatchInlineSnapshot(`"/3/gallery/r/wallstreetbets/time"`); 19 | 20 | expect( 21 | constructSubredditGalleryUrl({ 22 | subreddit: 'wallstreetbets', 23 | sort: 'top', 24 | window: 'day', 25 | }).pathname 26 | ).toMatchInlineSnapshot(`"/3/gallery/r/wallstreetbets/top/day"`); 27 | 28 | const { href, pathname } = constructSubredditGalleryUrl({ 29 | subreddit: 'wallstreetbets', 30 | sort: 'top', 31 | window: 'day', 32 | page: 2, 33 | }); 34 | expect(pathname).toMatchInlineSnapshot( 35 | `"/3/gallery/r/wallstreetbets/top/day/2"` 36 | ); 37 | expect(href).toMatchInlineSnapshot( 38 | `"https://api.imgur.com/3/gallery/r/wallstreetbets/top/day/2"` 39 | ); 40 | }); 41 | 42 | test('returns a gallery response', async () => { 43 | const accessToken = 'abc123'; 44 | const client = new ImgurClient({ accessToken }); 45 | const response = await getSubredditGallery(client, { 46 | subreddit: 'wallstreetbets', 47 | }); 48 | expect(response).toMatchInlineSnapshot(` 49 | { 50 | "data": [ 51 | { 52 | "description": "gallery-description", 53 | "id": "ans7sd", 54 | "images": [ 55 | { 56 | "description": null, 57 | "id": "4yMKKLTz", 58 | "link": "https://i.imgur.com/4yMKKLTz.jpg", 59 | "title": null, 60 | }, 61 | ], 62 | "link": "https://imgur.com/a/abc123", 63 | "title": "gallery-title", 64 | }, 65 | ], 66 | "headers": { 67 | "content-length": "253", 68 | "content-type": "application/json", 69 | }, 70 | "status": 200, 71 | "success": true, 72 | } 73 | `); 74 | }); 75 | -------------------------------------------------------------------------------- /example/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Imgur API test 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 |
19 | 20 | 21 | 22 | 23 |
24 | 25 | 69 | 70 | 71 | 72 | -------------------------------------------------------------------------------- /src/gallery/getGallery.test.ts: -------------------------------------------------------------------------------- 1 | import { ImgurClient } from '../client'; 2 | import { getGallery, GalleryOptions, constructGalleryUrl } from './getGallery'; 3 | import { test, expect } from 'vitest'; 4 | 5 | test('constructGalleryUrl', () => { 6 | expect( 7 | constructGalleryUrl({} as GalleryOptions).pathname 8 | ).toMatchInlineSnapshot(`"/3/gallery/hot/viral"`); 9 | 10 | expect( 11 | constructGalleryUrl({ section: 'hot' }).pathname 12 | ).toMatchInlineSnapshot(`"/3/gallery/hot/viral"`); 13 | 14 | expect( 15 | constructGalleryUrl({ section: 'hot', sort: 'top' }).pathname 16 | ).toMatchInlineSnapshot(`"/3/gallery/hot/top"`); 17 | 18 | expect( 19 | constructGalleryUrl({ section: 'top', window: 'day' }).pathname 20 | ).toMatchInlineSnapshot(`"/3/gallery/top/viral/day"`); 21 | 22 | expect( 23 | constructGalleryUrl({ section: 'user', sort: 'rising' }).pathname 24 | ).toMatchInlineSnapshot(`"/3/gallery/user/rising"`); 25 | 26 | const { href, pathname, search } = constructGalleryUrl({ 27 | section: 'user', 28 | sort: 'rising', 29 | showViral: true, 30 | mature: false, 31 | album_previews: true, 32 | }); 33 | expect(pathname).toMatchInlineSnapshot(`"/3/gallery/user/rising"`); 34 | expect(search).toMatchInlineSnapshot( 35 | `"?showViral=true&mature=false&album_previews=true"` 36 | ); 37 | expect(href).toMatchInlineSnapshot( 38 | `"https://api.imgur.com/3/gallery/user/rising?showViral=true&mature=false&album_previews=true"` 39 | ); 40 | }); 41 | 42 | test('returns an image response', async () => { 43 | const accessToken = 'abc123'; 44 | const client = new ImgurClient({ accessToken }); 45 | const response = await getGallery(client, { section: 'hot' }); 46 | expect(response).toMatchInlineSnapshot(` 47 | { 48 | "data": [ 49 | { 50 | "description": "gallery-description", 51 | "id": "ans7sd", 52 | "images": [ 53 | { 54 | "description": null, 55 | "id": "4yMKKLTz", 56 | "link": "https://i.imgur.com/4yMKKLTz.jpg", 57 | "title": null, 58 | }, 59 | ], 60 | "link": "https://imgur.com/a/abc123", 61 | "title": "gallery-title", 62 | }, 63 | ], 64 | "headers": { 65 | "content-length": "253", 66 | "content-type": "application/json", 67 | }, 68 | "status": 200, 69 | "success": true, 70 | } 71 | `); 72 | }); 73 | -------------------------------------------------------------------------------- /src/gallery/searchGallery.ts: -------------------------------------------------------------------------------- 1 | import { ImgurClient } from '../client'; 2 | import { SEARCH_GALLERY_ENDPOINT, IMGUR_API_PREFIX } from '../common/endpoints'; 3 | import { ImgurApiResponse, GalleryData } from '../common/types'; 4 | import { getImgurApiResponseFromResponse } from '../common/utils'; 5 | import { URL } from 'whatwg-url'; 6 | 7 | export type SearchOptions = { 8 | q?: string; 9 | query?: string; 10 | sort?: 'time' | 'viral'; 11 | page?: number; 12 | }; 13 | 14 | export type TopSearchOptions = Omit & { 15 | sort?: 'top'; 16 | window?: 'day' | 'week' | 'month' | 'year' | 'all'; 17 | }; 18 | 19 | export type AdvancedSearchQueryParameters = { 20 | q_all?: string; 21 | q_any?: string; 22 | q_exactly?: string; 23 | q_not?: string; 24 | q_type?: 'jpg' | 'png' | 'gif' | 'anigif' | 'album'; 25 | q_size_px?: 'small' | 'med' | 'big' | 'lrg' | 'huge'; 26 | }; 27 | 28 | const advancedParameters: Array = [ 29 | 'q_all', 30 | 'q_any', 31 | 'q_exactly', 32 | 'q_not', 33 | 'q_type', 34 | 'q_size_px', 35 | ]; 36 | 37 | export type SearchGalleryOptions = (SearchOptions | TopSearchOptions) & 38 | AdvancedSearchQueryParameters; 39 | 40 | export function constructSearchGalleryUrl(options: SearchGalleryOptions): URL { 41 | let uri = ''; 42 | 43 | if (options.sort) { 44 | uri += `/${options.sort}`; 45 | } 46 | 47 | if (options.sort === 'top' && options.window) { 48 | uri += `/${options.window}`; 49 | } 50 | 51 | if (options.page) { 52 | uri += `/${options.page}`; 53 | } 54 | 55 | const url = new URL(`${IMGUR_API_PREFIX}/${SEARCH_GALLERY_ENDPOINT}${uri}`); 56 | 57 | advancedParameters.forEach((param) => { 58 | if (options[param]?.length) { 59 | url.searchParams.append(param, options[param] as string); 60 | } 61 | }); 62 | 63 | if (!url.search) { 64 | const query = options.q || options.query; 65 | if (!query) { 66 | throw new Error('No query was provided'); 67 | } 68 | 69 | url.searchParams.append('q', query); 70 | } 71 | 72 | return url; 73 | } 74 | 75 | export async function searchGallery( 76 | client: ImgurClient, 77 | options: SearchGalleryOptions 78 | ): Promise> { 79 | const { pathname, search } = constructSearchGalleryUrl(options); 80 | // since we're using prefixUrl with got, we have to remove the starting slash or it'll throw 81 | const finalPathname = pathname.slice(1); 82 | 83 | return getImgurApiResponseFromResponse( 84 | await client 85 | .request({ url: finalPathname + search }) 86 | .catch((e) => e.response) 87 | ) as ImgurApiResponse; 88 | } 89 | -------------------------------------------------------------------------------- /src/mocks/handlers/authorize.ts: -------------------------------------------------------------------------------- 1 | import { HttpResponse } from 'msw'; 2 | 3 | const RequiredFieldErrorResponse = (method: string) => { 4 | return { 5 | data: { 6 | error: 'client_id and response_type are required', 7 | request: '/oauth/authorize', 8 | method, 9 | }, 10 | success: false, 11 | status: 400, 12 | }; 13 | }; 14 | 15 | const UnauthorizedErrorResponse = { 16 | data: { 17 | error: 'Unauthorized', 18 | request: '/oauth2/authorize', 19 | method: 'POST', 20 | }, 21 | success: false, 22 | status: 403, 23 | }; 24 | 25 | function createRedirectUrl(username: string) { 26 | return `https://somedomain.com#access_token=123accesstoken456&expires_in=315360000&token_type=bearer&refresh_token=123refrestoken456&account_username=${username}&account_id=123456`; 27 | } 28 | 29 | export const postHandler = async (request) => { 30 | const url = new URL(request.url); 31 | const clientId = url.searchParams.get('client_id'); 32 | const responseType = url.searchParams.get('response_type'); 33 | 34 | if (!(clientId && responseType)) { 35 | return HttpResponse.json(RequiredFieldErrorResponse('POST'), { 36 | status: 400, 37 | }); 38 | } 39 | 40 | const body = await request.json(); 41 | const { username, password, allow } = body; 42 | 43 | if (!(username && password && allow)) { 44 | return HttpResponse.json(UnauthorizedErrorResponse, { status: 403 }); 45 | } 46 | 47 | const redirectUrl = createRedirectUrl(username); 48 | 49 | return new HttpResponse(null, { 50 | status: 200, 51 | headers: { 52 | Location: redirectUrl, 53 | 'Set-Cookie': `authorize_token=${allow}; Path=/oauth2; Domain=.api.imgur.com; Secure; HttpOnly`, 54 | }, 55 | }); 56 | }; 57 | 58 | export const getHandler = (request) => { 59 | const url = new URL(request.url); 60 | const clientId = url.searchParams.get('client_id'); 61 | const responseType = url.searchParams.get('response_type'); 62 | 63 | if (!(clientId && responseType)) { 64 | return HttpResponse.json(RequiredFieldErrorResponse('GET'), { 65 | status: 400, 66 | }); 67 | } 68 | 69 | const mockAuthorizeToken = 'abcxyz'; 70 | const html = ` 71 | 72 |
73 | 74 | 75 | 76 |
77 | 78 | `; 79 | 80 | return new HttpResponse(html, { 81 | status: 200, 82 | headers: { 83 | 'Content-Type': 'text/html', 84 | 'Set-Cookie': `authorize_token=${mockAuthorizeToken}; Path=/oauth2; Domain=.api.imgur.com; Secure; HttpOnly`, 85 | }, 86 | }); 87 | }; 88 | -------------------------------------------------------------------------------- /src/gallery/getGallery.ts: -------------------------------------------------------------------------------- 1 | import { ImgurClient } from '../client'; 2 | import { GALLERY_ENDPOINT, IMGUR_API_PREFIX } from '../common/endpoints'; 3 | import { ImgurApiResponse, GalleryData } from '../common/types'; 4 | import { URL } from 'whatwg-url'; 5 | import { getImgurApiResponseFromResponse } from '../common/utils'; 6 | 7 | export type CommonSectionProps = { 8 | sort?: 'viral' | 'top' | 'time'; 9 | page?: number; 10 | }; 11 | 12 | export type HotSection = CommonSectionProps & { 13 | section: 'hot'; 14 | }; 15 | 16 | export type TopSection = CommonSectionProps & { 17 | section: 'top'; 18 | window?: 'day' | 'week' | 'month' | 'year' | 'all'; 19 | }; 20 | 21 | export type UserSection = Omit & { 22 | section: 'user'; 23 | sort?: 'viral' | 'top' | 'time' | 'rising'; 24 | }; 25 | 26 | export type SectionOptions = HotSection | TopSection | UserSection; 27 | 28 | export type PresentationOptions = { 29 | showViral?: boolean; 30 | mature?: boolean; 31 | album_previews?: boolean; 32 | }; 33 | 34 | export type GalleryOptions = SectionOptions & PresentationOptions; 35 | 36 | const defaultOptions: GalleryOptions = { 37 | section: 'hot', 38 | sort: 'viral', 39 | }; 40 | 41 | export function constructGalleryUrl(options: GalleryOptions): URL { 42 | const mergedOptions = Object.assign({}, defaultOptions, options); 43 | 44 | let uri = `${mergedOptions.section}`; 45 | 46 | if (mergedOptions.sort) { 47 | uri += `/${mergedOptions.sort}`; 48 | } 49 | 50 | if (mergedOptions.section === 'top' && mergedOptions.window) { 51 | uri += `/${mergedOptions.window}`; 52 | } 53 | 54 | if (mergedOptions.page) { 55 | uri += `/${mergedOptions.page}`; 56 | } 57 | 58 | const url = new URL(`${IMGUR_API_PREFIX}/${GALLERY_ENDPOINT}/${uri}`); 59 | 60 | if (mergedOptions.showViral !== undefined) { 61 | url.searchParams.append('showViral', mergedOptions.showViral.toString()); 62 | } 63 | 64 | if (mergedOptions.mature !== undefined) { 65 | url.searchParams.append('mature', mergedOptions.mature.toString()); 66 | } 67 | 68 | if (mergedOptions.album_previews !== undefined) { 69 | url.searchParams.append( 70 | 'album_previews', 71 | mergedOptions.album_previews.toString() 72 | ); 73 | } 74 | 75 | return url; 76 | } 77 | 78 | export async function getGallery( 79 | client: ImgurClient, 80 | options: GalleryOptions = defaultOptions 81 | ): Promise> { 82 | const { pathname } = constructGalleryUrl(options); 83 | // since we're using prefixUrl with got, we have to remove the starting slash or it'll throw 84 | const finalPathname = pathname.slice(1); 85 | 86 | return getImgurApiResponseFromResponse( 87 | await client.request({ url: finalPathname }).catch((e) => e.response) 88 | ) as ImgurApiResponse; 89 | } 90 | -------------------------------------------------------------------------------- /src/common/utils.ts: -------------------------------------------------------------------------------- 1 | import { AxiosHeaders, AxiosResponse } from 'axios'; 2 | import FormData from 'form-data'; 3 | import { ImgurApiResponse, Payload } from './types'; 4 | 5 | export function createForm(payload: string | Payload): FormData { 6 | const form = new FormData(); 7 | 8 | if (typeof payload === 'string') { 9 | form.append('image', payload); 10 | return form; 11 | } 12 | 13 | for (const [key, value] of Object.entries(payload)) { 14 | const supportedUploadObjectTypes = ['base64', 'stream']; 15 | if (supportedUploadObjectTypes.indexOf(key) !== -1) { 16 | if (supportedUploadObjectTypes.indexOf(payload.type as string) !== -1) { 17 | form.append(key, payload); 18 | } 19 | } else if (value) { 20 | form.append(key, value); 21 | } 22 | } 23 | 24 | form.getHeaders = form.getHeaders 25 | ? form.getHeaders 26 | : () => { 27 | return { 28 | 'Content-Type': 'multipart/form-data', 29 | }; 30 | }; 31 | 32 | return form; 33 | } 34 | 35 | export function getImgurApiResponseFromResponse( 36 | response: AxiosResponse 37 | ): ImgurApiResponse { 38 | let success = true; 39 | let headers = new AxiosHeaders(response?.headers ?? {}); 40 | let data; 41 | let status = 200; 42 | const responseIsValid = 43 | response && 44 | (typeof response.status !== 'undefined' || 45 | typeof response.data?.status !== 'undefined') && 46 | typeof response.data !== 'undefined'; 47 | const responseIsSuccess = responseIsValid && !!response.data.success; 48 | const responseIsError = 49 | responseIsValid && 50 | !responseIsSuccess && 51 | (typeof response.data.data?.error !== 'undefined' || 52 | typeof response.data.errors !== 'undefined'); 53 | 54 | const getResponseData = (d) => 55 | Array.isArray(d) ? d.map((t) => (responseIsError ? t.detail : t.data)) : d; 56 | 57 | if (typeof response === 'undefined') { 58 | data = 'response was empty'; 59 | status = 500; 60 | success = false; 61 | } else if (typeof response === 'string') { 62 | data = response as string; 63 | status = 500; 64 | success = false; 65 | } else if (responseIsSuccess) { 66 | status = response.data.status; 67 | headers = response.headers as AxiosHeaders; 68 | data = response.data.data.error 69 | ? response.data.data.error 70 | : response.data.data; 71 | } else { 72 | success = false; 73 | status = 74 | response.data.data?.error?.code ?? 75 | response.status ?? 76 | response.data.status; 77 | headers = response.headers as AxiosHeaders; 78 | data = getResponseData( 79 | responseIsError 80 | ? (response.data.errors ?? 81 | response.data.data.error.message ?? 82 | response.data.data.error) 83 | : (response.data.data ?? response.data.message ?? response.data) 84 | ); 85 | } 86 | 87 | return { 88 | headers, 89 | data, 90 | status, 91 | success, 92 | }; 93 | } 94 | 95 | export function hasPathOrName( 96 | obj: unknown 97 | ): obj is { path?: string; name?: string } { 98 | return ( 99 | typeof obj === 'object' && obj !== null && ('path' in obj || 'name' in obj) 100 | ); 101 | } 102 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "author": "Ken Eucker ", 3 | "name": "imgur", 4 | "description": "Unofficial JavaScript library for Imgur", 5 | "version": "2.5.0", 6 | "homepage": "https://github.com/keneucker/imgur", 7 | "license": "AGPL-3.0-or-later", 8 | "type": "module", 9 | "main": "./dist/imgur.cjs", 10 | "module": "./dist/imgur.js", 11 | "types": "./dist/index.d.ts", 12 | "exports": { 13 | ".": { 14 | "import": "./dist/imgur.js", 15 | "require": "./dist/imgur.cjs" 16 | } 17 | }, 18 | "keywords": [ 19 | "imgur", 20 | "edit", 21 | "images" 22 | ], 23 | "repository": { 24 | "type": "git", 25 | "url": "git://github.com/keneucker/imgur.git" 26 | }, 27 | "dependencies": { 28 | "axios": "^1.10.0", 29 | "form-data": "^4.0.3", 30 | "whatwg-url": "^14.2.0" 31 | }, 32 | "engines": { 33 | "node": ">=14" 34 | }, 35 | "files": [ 36 | "dist", 37 | "package.json", 38 | "LICENSE.md", 39 | "README.md" 40 | ], 41 | "scripts": { 42 | "test": "vitest run --reporter=verbose", 43 | "test:dev": "vitest", 44 | "test:ci": "vitest run --coverage", 45 | "run:dev": "node example/index.cjs", 46 | "run:browser": "vite example", 47 | "build:dev": "npm run build -- --watch", 48 | "build": "vite build && vite build --config vite.umd.config.ts", 49 | "typecheck": "tsc --noEmit", 50 | "clean": "rm -rf dist _site test/src/**/*.js test/src/**/*.d.ts", 51 | "format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"", 52 | "format:check": "prettier . --check ", 53 | "lint:fix": "prettier . --write && eslint . --fix", 54 | "lint:check": "eslint . && prettier . --check", 55 | "lint:release": "npm run format:check && npm run lint:check && npm run typecheck && echo '🤖 !linter ✅ success! 🤖'", 56 | "lint:staged": "npx --no-install lint-staged", 57 | "commit": "cz" 58 | }, 59 | "devDependencies": { 60 | "@commitlint/cli": "^19.8.1", 61 | "@commitlint/config-conventional": "^19.8.1", 62 | "@types/mock-fs": "^4.13.4", 63 | "@types/node": "^24.0.7", 64 | "@typescript-eslint/eslint-plugin": "^8.35.0", 65 | "@typescript-eslint/parser": "^8.35.0", 66 | "@vitest/coverage-v8": "^3.2.4", 67 | "axios-mock-adapter": "^2.1.0", 68 | "commitizen": "^4.3.1", 69 | "cz-conventional-changelog": "^3.3.0", 70 | "dotenv": "^17.0.0", 71 | "eslint": "^9.30.0", 72 | "eslint-config-prettier": "^10.1.5", 73 | "happy-dom": "^18.0.1", 74 | "lint-staged": "^16.1.2", 75 | "mock-fs": "^5.5.0", 76 | "msw": "^2.10.2", 77 | "prettier": "^3.6.2", 78 | "rollup-plugin-polyfill-node": "^0.13.0", 79 | "semantic-release": "^24.2.5", 80 | "ts-loader": "^9.5.2", 81 | "typescript": "^5.8.3", 82 | "undici": "^7.11.0", 83 | "vite": "^7.0.0", 84 | "vite-plugin-dts": "^4.5.4", 85 | "vite-plugin-static-copy": "^3.1.0", 86 | "vitest": "^3.2.4" 87 | }, 88 | "lint-staged": { 89 | "*.ts": [ 90 | "eslint . --fix", 91 | "vitest run" 92 | ], 93 | "*.{js,css,md,yml,yaml,json}": "prettier --write" 94 | }, 95 | "config": { 96 | "commitizen": { 97 | "path": "./node_modules/cz-conventional-changelog" 98 | } 99 | }, 100 | "commitlint": { 101 | "extends": [ 102 | "@commitlint/config-conventional" 103 | ] 104 | } 105 | } 106 | -------------------------------------------------------------------------------- /src/common/types.ts: -------------------------------------------------------------------------------- 1 | export interface AccessToken { 2 | accessToken?: string; 3 | refreshToken?: string; 4 | } 5 | 6 | export interface RapidApiKey { 7 | rapidApiHost?: string; 8 | rapidApiKey?: string; 9 | } 10 | 11 | export interface ClientId { 12 | clientId?: string; 13 | clientSecret?: string; 14 | } 15 | 16 | export interface Credentials extends AccessToken, ClientId, RapidApiKey {} 17 | 18 | export interface ImgurTokenResponse { 19 | account_username?: string; 20 | access_token: string; 21 | refresh_token: string; 22 | token_type?: string; 23 | expires_in?: number; 24 | } 25 | 26 | export function isAccessToken(arg: unknown): arg is AccessToken { 27 | return (arg as AccessToken).accessToken !== undefined; 28 | } 29 | 30 | export function isRefreshToken(arg: unknown): arg is AccessToken { 31 | return (arg as AccessToken).refreshToken !== undefined; 32 | } 33 | 34 | export function isClientId(arg: unknown): arg is ClientId { 35 | return (arg as ClientId).clientId !== undefined; 36 | } 37 | 38 | interface CommonData { 39 | id: string; 40 | title: string | null; 41 | description: string | null; 42 | datetime: number; 43 | link: string; 44 | 45 | ad_config?: { 46 | safeFlags: string[]; 47 | highRiskFlags: string[]; 48 | unsafeFlags: string[]; 49 | wallUnsafeFlags: string[]; 50 | showsAds: boolean; 51 | }; 52 | ad_type: number; 53 | ad_url: string; 54 | 55 | account_url: string | null; 56 | account_id: string | null; 57 | favorite: boolean; 58 | is_ad: boolean; 59 | is_album: boolean; 60 | in_gallery: boolean; 61 | in_most_viral: boolean; 62 | nsfw: boolean | null; 63 | section: string | null; 64 | tags: Array<{ 65 | name: string; 66 | display_name: string; 67 | followers: number; 68 | total_items: number; 69 | following: boolean; 70 | is_whitelisted: boolean; 71 | background_hash: string; 72 | thumbnail_hash: string | null; 73 | accent: string; 74 | background_is_animated: boolean; 75 | thumbnail_is_animated: boolean; 76 | is_promoted: boolean; 77 | description: string; 78 | logo_hash: string | null; 79 | logo_destination_url: string | null; 80 | description_annotations: Record; 81 | }>; 82 | topic: string | null; 83 | topic_id: string | null; 84 | vote: null; 85 | 86 | comment_count: number | null; 87 | favorite_count: number | null; 88 | ups: number | null; 89 | downs: number | null; 90 | score: number | null; 91 | points: number | null; 92 | views: number; 93 | } 94 | export interface ImageData extends CommonData { 95 | type: string; 96 | width: number; 97 | height: number; 98 | size: number; 99 | deletehash?: string; 100 | bandwidth: number; 101 | animated: boolean; 102 | has_sound: boolean; 103 | edited: string; 104 | mp4_size?: number; 105 | mp4?: string; 106 | gifv?: string; 107 | hls?: string; 108 | looping?: boolean; 109 | processing?: { 110 | status: 'pending' | 'completed'; 111 | }; 112 | } 113 | 114 | export interface AlbumData extends CommonData { 115 | cover: string | null; 116 | cover_width: number | null; 117 | cover_height: number | null; 118 | layout: string; 119 | privacy: string; 120 | include_album_ads: boolean; 121 | images: ImageData[]; 122 | images_count: number; 123 | deletehash: string; 124 | } 125 | 126 | export interface AccountData { 127 | id: number; 128 | url: string; 129 | bio: string; 130 | avatar: string; 131 | reputation: number; 132 | reputation_name: string; 133 | created: number; 134 | pro_expiration: boolean; 135 | user_follow: { 136 | status: boolean; 137 | }; 138 | } 139 | 140 | export type GalleryData = Array; 141 | export interface Payload { 142 | image?: string | Buffer | ReadableStream; 143 | type?: 'stream' | 'url' | 'base64'; 144 | name?: string; 145 | title?: string; 146 | description?: string; 147 | album?: string; 148 | disable_audio?: '1' | '0'; 149 | } 150 | export interface ImgurApiResponse< 151 | T = 152 | | Record 153 | | Record[] 154 | | string 155 | | string[] 156 | | boolean 157 | | ImageData 158 | | GalleryData 159 | | AlbumData 160 | | AccountData, 161 | > { 162 | headers: Record; 163 | data: T; 164 | status: number; 165 | success: boolean; 166 | } 167 | -------------------------------------------------------------------------------- /src/client.ts: -------------------------------------------------------------------------------- 1 | import { EventEmitter } from 'events'; 2 | import { getAuthorizationHeader } from './getAuthorizationHeader'; 3 | import { 4 | deleteImage, 5 | favoriteImage, 6 | getImage, 7 | upload, 8 | updateImage, 9 | UpdateImagePayload, 10 | } from './image'; 11 | import { 12 | GalleryOptions, 13 | getGallery, 14 | getSubredditGallery, 15 | SubredditGalleryOptions, 16 | searchGallery, 17 | SearchGalleryOptions, 18 | } from './gallery'; 19 | import { getAlbum, createAlbum } from './album'; 20 | import { getAccount, getAlbums, getAlbumsIds } from './account'; 21 | import { IMGUR_API_PREFIX } from './common/endpoints'; 22 | import type { 23 | AccountData, 24 | AlbumData, 25 | Credentials, 26 | GalleryData, 27 | ImageData, 28 | ImgurApiResponse, 29 | Payload, 30 | } from './common/types'; 31 | 32 | const USERAGENT = 'imgur (https://github.com/keneucker/imgur)'; 33 | 34 | import axios, { 35 | AxiosInstance, 36 | AxiosResponse, 37 | AxiosRequestConfig, 38 | InternalAxiosRequestConfig, 39 | } from 'axios'; 40 | export type { Credentials as ImgurCredentials, ImgurApiResponse }; 41 | export class ImgurClient extends EventEmitter { 42 | private plainFetcher: AxiosInstance; 43 | private fetcher: AxiosInstance; 44 | 45 | constructor(public credentials: Credentials) { 46 | super(); 47 | 48 | this.credentials.rapidApiHost = credentials.rapidApiKey?.length 49 | ? (credentials.rapidApiHost ?? 'imgur-apiv3.p.rapidapi.com') 50 | : credentials.rapidApiHost; 51 | const headers = 52 | typeof window !== 'undefined' 53 | ? {} 54 | : { 55 | 'user-agent': USERAGENT, 56 | }; 57 | 58 | this.plainFetcher = axios.create({ 59 | baseURL: IMGUR_API_PREFIX, 60 | headers, 61 | responseType: 'json', 62 | }); 63 | this.fetcher = axios.create({ 64 | baseURL: credentials.rapidApiKey?.length 65 | ? `https://${this.credentials.rapidApiHost}` 66 | : IMGUR_API_PREFIX, 67 | headers, 68 | responseType: 'json', 69 | }); 70 | this.fetcher.interceptors.request.use( 71 | async (config: InternalAxiosRequestConfig) => { 72 | config.headers.authorization = await getAuthorizationHeader(this); 73 | 74 | if (credentials.rapidApiKey?.length) { 75 | config.headers['x-rapidapi-host'] = credentials.rapidApiHost; 76 | config.headers['x-rapidapi-key'] = credentials.rapidApiKey; 77 | } 78 | return config; 79 | }, 80 | (e: Error) => Promise.reject(e) 81 | ); 82 | } 83 | 84 | plainRequest(options: AxiosRequestConfig): Promise> { 85 | return this.plainFetcher(options); 86 | } 87 | 88 | request(options: AxiosRequestConfig = {}): Promise> { 89 | return this.fetcher(options); 90 | } 91 | 92 | deleteImage(imageHash: string): Promise> { 93 | return deleteImage(this, imageHash); 94 | } 95 | 96 | favoriteImage(imageHash: string): Promise> { 97 | return favoriteImage(this, imageHash); 98 | } 99 | 100 | getAlbum(albumHash: string): Promise> { 101 | return getAlbum(this, albumHash); 102 | } 103 | 104 | getAccount(account: string): Promise> { 105 | return getAccount(this, account); 106 | } 107 | 108 | getAlbums( 109 | account: string, 110 | page?: number 111 | ): Promise> { 112 | return getAlbums(this, account, page); 113 | } 114 | 115 | createAlbum( 116 | title?: string, 117 | description?: string 118 | ): Promise> { 119 | return createAlbum(this, title, description); 120 | } 121 | 122 | getAlbumsIds( 123 | account: string, 124 | page?: number 125 | ): Promise> { 126 | return getAlbumsIds(this, account, page); 127 | } 128 | 129 | getGallery(options: GalleryOptions): Promise> { 130 | return getGallery(this, options); 131 | } 132 | 133 | getSubredditGallery( 134 | options: SubredditGalleryOptions 135 | ): Promise> { 136 | return getSubredditGallery(this, options); 137 | } 138 | 139 | searchGallery( 140 | options: SearchGalleryOptions 141 | ): Promise> { 142 | return searchGallery(this, options); 143 | } 144 | 145 | getImage(imageHash: string): Promise> { 146 | return getImage(this, imageHash); 147 | } 148 | 149 | updateImage(payload: UpdateImagePayload): Promise> { 150 | return updateImage(this, payload); 151 | } 152 | 153 | upload(payload: Payload): Promise> { 154 | return upload(this, payload); 155 | } 156 | } 157 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | We as members, contributors, and leaders pledge to make participation in our 6 | community a harassment-free experience for everyone, regardless of age, body 7 | size, visible or invisible disability, ethnicity, sex characteristics, gender 8 | identity and expression, level of experience, education, socio-economic status, 9 | nationality, personal appearance, race, caste, color, religion, or sexual identity 10 | and orientation. 11 | 12 | We pledge to act and interact in ways that contribute to an open, welcoming, 13 | diverse, inclusive, and healthy community. 14 | 15 | ## Our Standards 16 | 17 | Examples of behavior that contributes to a positive environment for our 18 | community include: 19 | 20 | - Demonstrating empathy and kindness toward other people 21 | - Being respectful of differing opinions, viewpoints, and experiences 22 | - Giving and gracefully accepting constructive feedback 23 | - Accepting responsibility and apologizing to those affected by our mistakes, 24 | and learning from the experience 25 | - Focusing on what is best not just for us as individuals, but for the 26 | overall community 27 | 28 | Examples of unacceptable behavior include: 29 | 30 | - The use of sexualized language or imagery, and sexual attention or 31 | advances of any kind 32 | - Trolling, insulting or derogatory comments, and personal or political attacks 33 | - Public or private harassment 34 | - Publishing others' private information, such as a physical or email 35 | address, without their explicit permission 36 | - Other conduct which could reasonably be considered inappropriate in a 37 | professional setting 38 | 39 | ## Enforcement Responsibilities 40 | 41 | Community leaders are responsible for clarifying and enforcing our standards of 42 | acceptable behavior and will take appropriate and fair corrective action in 43 | response to any behavior that they deem inappropriate, threatening, offensive, 44 | or harmful. 45 | 46 | Community leaders have the right and responsibility to remove, edit, or reject 47 | comments, commits, code, wiki edits, issues, and other contributions that are 48 | not aligned to this Code of Conduct, and will communicate reasons for moderation 49 | decisions when appropriate. 50 | 51 | ## Scope 52 | 53 | This Code of Conduct applies within all community spaces, and also applies when 54 | an individual is officially representing the community in public spaces. 55 | Examples of representing our community include using an official e-mail address, 56 | posting via an official social media account, or acting as an appointed 57 | representative at an online or offline event. 58 | 59 | ## Enforcement 60 | 61 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 62 | reported to the community leaders responsible for enforcement at 63 | [INSERT CONTACT METHOD]. 64 | All complaints will be reviewed and investigated promptly and fairly. 65 | 66 | All community leaders are obligated to respect the privacy and security of the 67 | reporter of any incident. 68 | 69 | ## Enforcement Guidelines 70 | 71 | Community leaders will follow these Community Impact Guidelines in determining 72 | the consequences for any action they deem in violation of this Code of Conduct: 73 | 74 | ### 1. Correction 75 | 76 | **Community Impact**: Use of inappropriate language or other behavior deemed 77 | unprofessional or unwelcome in the community. 78 | 79 | **Consequence**: A private, written warning from community leaders, providing 80 | clarity around the nature of the violation and an explanation of why the 81 | behavior was inappropriate. A public apology may be requested. 82 | 83 | ### 2. Warning 84 | 85 | **Community Impact**: A violation through a single incident or series 86 | of actions. 87 | 88 | **Consequence**: A warning with consequences for continued behavior. No 89 | interaction with the people involved, including unsolicited interaction with 90 | those enforcing the Code of Conduct, for a specified period of time. This 91 | includes avoiding interactions in community spaces as well as external channels 92 | like social media. Violating these terms may lead to a temporary or 93 | permanent ban. 94 | 95 | ### 3. Temporary Ban 96 | 97 | **Community Impact**: A serious violation of community standards, including 98 | sustained inappropriate behavior. 99 | 100 | **Consequence**: A temporary ban from any sort of interaction or public 101 | communication with the community for a specified period of time. No public or 102 | private interaction with the people involved, including unsolicited interaction 103 | with those enforcing the Code of Conduct, is allowed during this period. 104 | Violating these terms may lead to a permanent ban. 105 | 106 | ### 4. Permanent Ban 107 | 108 | **Community Impact**: Demonstrating a pattern of violation of community 109 | standards, including sustained inappropriate behavior, harassment of an 110 | individual, or aggression toward or disparagement of classes of individuals. 111 | 112 | **Consequence**: A permanent ban from any sort of public interaction within 113 | the community. 114 | 115 | ## Attribution 116 | 117 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], 118 | version 2.0, available at 119 | [https://www.contributor-covenant.org/version/2/0/code_of_conduct.html][v2.0]. 120 | 121 | Community Impact Guidelines were inspired by 122 | [Mozilla's code of conduct enforcement ladder][mozilla coc]. 123 | 124 | For answers to common questions about this code of conduct, see the FAQ at 125 | [https://www.contributor-covenant.org/faq][faq]. Translations are available 126 | at [https://www.contributor-covenant.org/translations][translations]. 127 | 128 | [homepage]: https://www.contributor-covenant.org 129 | [v2.0]: https://www.contributor-covenant.org/version/2/0/code_of_conduct.html 130 | [mozilla coc]: https://github.com/mozilla/diversity 131 | [faq]: https://www.contributor-covenant.org/faq 132 | [translations]: https://www.contributor-covenant.org/translations 133 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |

imgur

2 |

Unofficial JavaScript library for the Imgur.com API

3 |

4 | 5 | npm version 6 | 7 | 8 | Build states 9 | 10 |

11 |

12 | 13 | Join the community on GitHub Discussions 14 | 15 |

16 | 17 | ## Installation 18 | 19 | ```shell 20 | npm install imgur 21 | ``` 22 | 23 | ## Usage 24 | 25 | ### Migrating to version 2 26 | 27 | Version 2 of the imgur api drops automatic support for filesystem usage. For uploading files from a filesystem, please see the examples using `createReadStream`. 28 | 29 | ### Import and instantiate with credentials: 30 | 31 | ```ts 32 | // ESModule syntax 33 | import { ImgurClient } from 'imgur'; 34 | 35 | // CommonJS syntax 36 | const { ImgurClient } = require('imgur'); 37 | 38 | // browser script include 39 | const client = new imgur({ clientId: env.CLIENT_ID }); 40 | 41 | // if you already have an access token acquired 42 | const client = new ImgurClient({ accessToken: process.env.ACCESS_TOKEN }); 43 | 44 | // or your client ID 45 | const client = new ImgurClient({ clientId: process.env.CLIENT_ID }); 46 | 47 | // all credentials with a refresh token, in order to get access tokens automatically 48 | const client = new ImgurClient({ 49 | clientId: process.env.CLIENT_ID, 50 | clientSecret: process.env.CLIENT_SECRET, 51 | refreshToken: process.env.REFRESH_TOKEN, 52 | }); 53 | ``` 54 | 55 | If you don't have any credentials, you'll need to: 56 | 57 | 1. [Create an Imgur account](https://imgur.com/register) 58 | 1. [Register an application](https://api.imgur.com/#registerapp) 59 | 60 | ### **⚠️ For brevity, the rest of the examples will leave out the import and/or instantiation step.** 61 | 62 | ### Upload one or more images and videos 63 | 64 | ```ts 65 | // upload multiple images via fs.createReadStream (node) 66 | const response = await client.upload({ 67 | image: createReadStream('/home/kai/dank-meme.jpg'), 68 | type: 'stream', 69 | }); 70 | console.log(response.data); 71 | ``` 72 | 73 | If you want to provide metadata, such as a title, description, etc., then pass an object instead of a string: 74 | 75 | ```ts 76 | // upload image via url 77 | const response = await client.upload({ 78 | image: 'https://i.imgur.com/someImageHash', 79 | title: 'Meme', 80 | description: 'Dank Meme', 81 | }); 82 | console.log(response.data); 83 | ``` 84 | 85 | Acceptable key/values match what [the Imgur API expects](https://apidocs.imgur.com/#c85c9dfc-7487-4de2-9ecd-66f727cf3139): 86 | 87 | | Key | Description | 88 | | --------------- | ----------------------------------------------------------------------------------------------------------------------------------- | 89 | | `image` | A string, stream, or buffer that is a URL pointing to a remote image or video (up to 10MB) | 90 | | `album` | The id of the album you want to add the media to. For anonymous albums, album should be the deletehash that is returned at creation | 91 | | `type` | The type of the media that's being transmitted; `stream`, `base64` or `url` | 92 | | `name` | The name of the media. This is automatically detected, but you can override | 93 | | `title` | The title of the media | 94 | | `description` | The description of the media | 95 | | `disable_audio` | `1` will remove the audio track from a video file | 96 | 97 | ### Upload and track progress of uploads 98 | 99 | Instances of `ImgurClient` emit `uploadProgress` events so that you can track progress with event listeners. 100 | 101 | ```ts 102 | const client = new ImgurClient({ accessToken: process.env.ACCESS_TOKEN }); 103 | 104 | client.on('uploadProgress', (progress) => console.log(progress)); 105 | await client.upload('/home/kai/cat.mp4'); 106 | ``` 107 | 108 | The progress object looks like the following: 109 | 110 | ```ts 111 | { 112 | percent: 1, 113 | transferred: 577, 114 | total: 577, 115 | id: '/home/user/trailer.mp4' 116 | } 117 | ``` 118 | 119 | | Key | Description | 120 | | ------------- | ------------------------------------------------------------------------------------------------- | 121 | | `percent` | 0 to 1, measures the percentage of upload (e.g., 0, 0.5, 0.8, 1). Basically `transferred / total` | 122 | | `transferred` | total number of bytes transferred thus far | 123 | | `total` | total number of bytes to be transferred | 124 | | `id` | unique id for the media being transferred; useful when uploading multiple things concurrently | 125 | 126 | ### Delete an image 127 | 128 | Requires an image hash or delete hash, which are obtained in an image upload response 129 | 130 | ```ts 131 | client.deleteImage('someImageHash'); 132 | ``` 133 | 134 | ### Update image information 135 | 136 | Update the title and/or description of an image 137 | 138 | ```ts 139 | client.updateImage({ 140 | imageHash: 'someImageHash', 141 | title: 'A new title', 142 | description: 'A new description', 143 | }); 144 | ``` 145 | 146 | Update multiple images at once: 147 | 148 | ```ts 149 | client.updateImage({ 150 | imageHash: 'someImageHash', 151 | title: 'A new title', 152 | description: 'A new description', 153 | }); 154 | ``` 155 | 156 | Favorite an image: 157 | 158 | ```ts 159 | client.favoriteImage('someImageHash'); 160 | ``` 161 | 162 | ### Get gallery images 163 | 164 | ```ts 165 | client.getGallery({ 166 | section: 'hot', 167 | sort: 'viral', 168 | mature: false, 169 | }); 170 | ``` 171 | 172 | `getGallery()` accepts an object of type `GalleryOptions`. The follow options are available: 173 | 174 | | Key | Required | Description | 175 | | ---------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | 176 | | `section` | required | `hot` \| `top` \| `user` | 177 | | `sort` | optional | `viral` \| `top` \| `time` \| `rising` (only available with user section). Defaults to viral | 178 | | `page` | optional | `number` - the data paging number | 179 | | `window` | optional | Change the date range of the request if the section is `top`. Accepted values are `day` \| `week` \| `month` \| `year` \| `all`. Defaults to `day` | 180 | | `showViral` | optional | `true` \| `false` - Show or hide viral images from the `user` section. Defaults to `true` | 181 | | `mature` | optional | `true` \| `false` - Show or hide mature (nsfw) images in the response section. Defaults to `false`. NOTE: This parameter is only required if un-authed. The response for authed users will respect their account setting | 182 | | `album_previews` | optional | `true` \| `false` - Include image metadata for gallery posts which are albums | 183 | 184 | ### Get subreddit gallery images 185 | 186 | ```ts 187 | client.getSubredditGallery({ 188 | subreddit: 'wallstreetbets', 189 | sort: 'time', 190 | }); 191 | ``` 192 | 193 | `getSubredditGallery()` accepts an object of type `SubredditGalleryOptions`. The follow options are available: 194 | 195 | | Key | Required | Description | 196 | | ----------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------- | 197 | | `subreddit` | required | A valid subreddit name | 198 | | `sort` | optional | `time` \| `top` - defaults to time | 199 | | `page` | optional | `number` - the data paging number | 200 | | `window` | optional | Change the date range of the request if the section is `top`. Accepted values are `day` \| `week` \| `month` \| `year` \| `all`. Defaults to `week` | 201 | 202 | ### Search the gallery 203 | 204 | ```ts 205 | client.searchGallery({ 206 | query: 'title: memes', 207 | }); 208 | ``` 209 | 210 | `searchGallery()` accepts an object of type `SearchGalleryOptions`. The follow options are available: 211 | 212 | | Key | Required | Description | 213 | | -------------- | -------- | --------------------------------------------------------------------- | ------ | ------- | ------ | ------------------------- | 214 | | `query` or `q` | required | Query string | 215 | | `sort` | optional | `time` \| `viral` \| `top` - defaults to time | 216 | | `page` | optional | `number` - the data paging number | 217 | | `window` | optional | Change the date range of the request if the sort is `top` -- to `day` | `week` | `month` | `year` | `all`, defaults to `all`. | 218 | 219 | Additionally, the following advanced search query options can be set (NOTE: if any of the below are set in the options, the `query` option is ignored and these will take precedent): 220 | 221 | | Key | Required | Description | 222 | | ----------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | 223 | | `q_all` | optional | Search for all of these words (and) | 224 | | `q_any` | optional | Search for any of these words (or) | 225 | | `q_exactly` | optional | Search for exactly this word or phrase | 226 | | `q_not` | optional | Exclude results matching this string | 227 | | `q_type` | optional | Show results for any file type, `jpg` \| `png` \| `gif` \| `anigif` (animated gif) \| `album` | 228 | | `q_size_px` | optional | Size ranges, `small` (500 pixels square or less) \| `med` (500 to 2,000 pixels square) \| `big` (2,000 to 5,000 pixels square) \| `lrg` (5,000 to 10,000 pixels square) \| `huge` (10,000 square pixels and above) | 229 | 230 | ### Get album info 231 | 232 | ```ts 233 | const album = await client.getAlbum('XtMnA'); 234 | ``` 235 | -------------------------------------------------------------------------------- /src/image/upload.test.ts: -------------------------------------------------------------------------------- 1 | import { describe, test, expect } from 'vitest'; 2 | 3 | // import { ImgurClient } from '../client'; 4 | // import { upload } from './upload'; 5 | // import { PassThrough } from 'stream'; 6 | // // import { ReadStream } from 'fs'; 7 | // // interface FileUpload { 8 | // // filename: string; 9 | // // mimetype: string; 10 | // // encoding: string; 11 | // // createReadStream(): ReadStream; 12 | // // } 13 | 14 | // // const mockReadStream = { pipe: jest.fn() }; 15 | // // const mockPngFile: FileUpload = { 16 | // // filename: '1x1.png', 17 | // // mimetype: 'image/png', 18 | // // encoding: '7bit', 19 | // // createReadStream: jest.fn().mockReturnValueOnce(mockReadStream), 20 | // // }; 21 | // // const mockMp4File: FileUpload = { 22 | // // filename: 'small.mp4', 23 | // // mimetype: 'video/mp4', 24 | // // encoding: '7bit', 25 | // // createReadStream: jest.fn().mockReturnValueOnce(mockReadStream), 26 | // // }; 27 | 28 | describe('test imgur uploads', () => { 29 | test('no tests ready because issues', async () => { 30 | expect(true).toBe(true); 31 | }); 32 | }); 33 | // test('upload one image via url string, receive one response', async () => { 34 | // const accessToken = 'abc123'; 35 | // const client = new ImgurClient({ accessToken }); 36 | // const response = await upload(client, { 37 | // image: 'https://i.imgur.com/JK9ybyj.jpg', 38 | // type: 'url', 39 | // }); 40 | // expect(response).toMatchInlineSnapshot(` 41 | // { 42 | // "data": { 43 | // "deletehash": "jyby9KJ", 44 | // "description": null, 45 | // "id": "JK9ybyj", 46 | // "link": "https://i.imgur.com/JK9ybyj.jpg", 47 | // "title": null, 48 | // }, 49 | // "status": 200, 50 | // "success": true, 51 | // } 52 | // `); 53 | // }); 54 | 55 | // test('upload multiple images via array of path strings, receive multiple responses', async () => { 56 | // const accessToken = 'abc123'; 57 | // const client = new ImgurClient({ accessToken }); 58 | // const response = await upload(client, [ 59 | // { image: 'https://i.imgur.com/JK9ybyj.jpg' }, 60 | // { image: 'https://i.imgur.com/JK9ybyj.jpg' }, 61 | // ]); 62 | // expect(response).toMatchInlineSnapshot(` 63 | // [ 64 | // { 65 | // "data": { 66 | // "deletehash": "jyby9KJ", 67 | // "description": null, 68 | // "id": "JK9ybyj", 69 | // "link": "https://i.imgur.com/JK9ybyj.jpg", 70 | // "title": null, 71 | // }, 72 | // "status": 200, 73 | // "success": true, 74 | // }, 75 | // { 76 | // "data": { 77 | // "deletehash": "jyby9KJ", 78 | // "description": null, 79 | // "id": "JK9ybyj", 80 | // "link": "https://i.imgur.com/JK9ybyj.jpg", 81 | // "title": null, 82 | // }, 83 | // "status": 200, 84 | // "success": true, 85 | // }, 86 | // ] 87 | // `); 88 | // }); 89 | 90 | // test('upload one image via bas64 payload type, receive one response', async () => { 91 | // const accessToken = 'abc123'; 92 | // const client = new ImgurClient({ accessToken }); 93 | // const response = await upload(client, { 94 | // stream: new PassThrough(), 95 | // title: 'dank meme', 96 | // description: 'the dankiest of dank memes', 97 | // }); 98 | // expect(response).toMatchInlineSnapshot(` 99 | // { 100 | // "data": { 101 | // "deletehash": "jyby9KJ", 102 | // "description": null, 103 | // "id": "JK9ybyj", 104 | // "link": "https://i.imgur.com/JK9ybyj.jpg", 105 | // "title": null, 106 | // }, 107 | // "status": 200, 108 | // "success": true, 109 | // } 110 | // `); 111 | // }); 112 | 113 | // test('upload multiple images via an array of base64 payload type, receive multiple response', async () => { 114 | // const accessToken = 'abc123'; 115 | // const client = new ImgurClient({ accessToken }); 116 | // const response = await upload(client, [ 117 | // { 118 | // base64: 119 | // 'data:image/png;base64,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', 120 | // title: 'dank meme', 121 | // description: 'the dankiest of dank memes', 122 | // }, 123 | // { 124 | // base64: 125 | // 'data:image/png;base64,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', 126 | // title: 'this is funny', 127 | // description: '🤣', 128 | // }, 129 | // ]); 130 | // expect(response).toMatchInlineSnapshot(` 131 | // [ 132 | // { 133 | // "data": { 134 | // "deletehash": "jyby9KJ", 135 | // "description": null, 136 | // "id": "JK9ybyj", 137 | // "link": "https://i.imgur.com/JK9ybyj.jpg", 138 | // "title": null, 139 | // }, 140 | // "status": 200, 141 | // "success": true, 142 | // }, 143 | // { 144 | // "data": { 145 | // "deletehash": "jyby9KJ", 146 | // "description": null, 147 | // "id": "JK9ybyj", 148 | // "link": "https://i.imgur.com/JK9ybyj.jpg", 149 | // "title": null, 150 | // }, 151 | // "status": 200, 152 | // "success": true, 153 | // }, 154 | // ] 155 | // `); 156 | // }); 157 | 158 | // test('upload a video, disable sound', async () => { 159 | // const accessToken = 'abc123'; 160 | // const client = new ImgurClient({ accessToken }); 161 | // const response = await upload(client, { 162 | // stream: new PassThrough(), 163 | // title: 'trailer for my new stream', 164 | // description: 'yolo', 165 | // disable_audio: '1', 166 | // }); 167 | // expect(response).toMatchInlineSnapshot(` 168 | // { 169 | // "data": { 170 | // "deletehash": "jyby9KJ", 171 | // "description": null, 172 | // "id": "JK9ybyj", 173 | // "link": "https://i.imgur.com/JK9ybyj.jpg", 174 | // "title": null, 175 | // }, 176 | // "status": 200, 177 | // "success": true, 178 | // } 179 | // `); 180 | // }); 181 | 182 | // test('upload failure results in captured response', async () => { 183 | // const accessToken = 'abc123'; 184 | // const client = new ImgurClient({ accessToken }); 185 | // const response = await upload(client, { 186 | // title: 'trailer for my new stream', 187 | // description: 'yolo', 188 | // disable_audio: '1', 189 | // }); 190 | // expect(response).toMatchInlineSnapshot(` 191 | // { 192 | // "data": { 193 | // "deletehash": "jyby9KJ", 194 | // "description": null, 195 | // "id": "JK9ybyj", 196 | // "link": "https://i.imgur.com/JK9ybyj.jpg", 197 | // "title": null, 198 | // }, 199 | // "status": 200, 200 | // "success": true, 201 | // } 202 | // `); 203 | // }); 204 | 205 | // // test('upload progress event emitter', async () => { 206 | // // const accessToken = 'abc123'; 207 | // // const stream = createReadStream('/home/user/trailer.mp4'); 208 | // // const client = new ImgurClient({ accessToken }); 209 | // // const eventHandler = jest.fn(); 210 | // // client.on('uploadProgress', eventHandler); 211 | 212 | // // await upload(client, { 213 | // // stream, 214 | // // title: 'trailer for my new stream', 215 | // // description: 'yolo', 216 | // // disable_audio: '1', 217 | // // }); 218 | // // expect(eventHandler).toBeCalledWith( 219 | // // expect.objectContaining({ 220 | // // id: expect.any(String), 221 | // // percent: expect.any(Number), 222 | // // total: expect.any(Number), 223 | // // transferred: expect.any(Number), 224 | // // }) 225 | // // ); 226 | // // }); 227 | // }); 228 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | 633 | Copyright (C) 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published 637 | by the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . 662 | --------------------------------------------------------------------------------