All files the-tv-db.ts

86.09% Statements 99/115
76.92% Branches 50/65
95.65% Functions 44/46
86.61% Lines 97/112

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 3161x 1x 1x                   67x 20x     20x 20x                                                       1x       19x     19x 19x 19x           19x             24x 1x   24x       1x   1x   1x             5x 5x 5x 7x         7x 7x   5x                       3x           3x   3x 1x 2x 1x         1x     1x 1x 1x 2x         2x 2x     1x             2x         1x 1x 1x       2x   2x 2x 2x   1x       2x         2x 2x     1x 1x       2x         2x 2x     1x 1x       13x           13x 1x         12x 12x     13x                 3x 3x     3x                 22x 22x 22x 22x   22x 22x         22x 22x 22x                                                 1x               1x 1x       1x 6x 7x 3x   4x         1x 27x 1x   26x 1x   25x     1x 22x 20x   2x       6x 6x    
import fetch, { Response } from 'node-fetch'
import { NotFound, Timeout } from './custom-erros'
import AbortController from 'abort-controller'
import {
  TheTvDbShow,
  TheTvDbShowEpisode,
  TheTvDbShowEpisodePage,
  TheTvDbUpdatedShowId,
  TheTvDbEpisode,
  TheTvDbShowImage
} from './types'
 
const noop: (msg: string) => void = () => undefined
const logWrapper = (log: (msg: string) => void, msg: string) => <T>(
  val: T
): T => {
  log(msg)
  return val
}
 
interface Options {
  /**
    First timeout
  */
  timeout?: number
 
  /**
    Canculate next timeout if the first timeout was met.
    @example
 
    const defaultNextTimeout = (currentTimeout: number) => {
      if (currentTimeout > 10000) {
        return null // Throw an timeout error
      }
      return currentTimeout + 1000 // timeout for the next try
    }
  */
  nextTimeout?: (currentTimeout: number) => number | null
 
  /**
   * Custom fetch function
   */
  fetch?: typeof fetch
}
 
export class TheTvDb {
  private apikey: string
  private fetch: typeof fetch
  private options: Required<Omit<Options, 'fetch'>>
  jwt: Promise<string> | undefined = undefined
 
  constructor(apikey: string, options?: Options) {
    this.apikey = apikey
    this.fetch = options?.fetch || fetch
    const defaultNextTimeout = (currentTimeout: number) => {
      if (currentTimeout > 4000) {
        return null
      }
      return currentTimeout + 1000
    }
    this.options = {
      timeout: options?.timeout || 2000,
      nextTimeout: options?.nextTimeout || defaultNextTimeout
    }
  }
 
  get token() {
    if (!this.jwt) {
      this.jwt = this.fetchToken()
    }
    return this.jwt
  }
 
  fetchShow(theTvDbId: number, log = noop): Promise<TheTvDbShow> {
    return this.get('https://api.thetvdb.com/series/' + theTvDbId, log)
      .then(handelHttpError)
      .then(res => res.json())
      .then(logWrapper(log, `Done, getting back`))
      .then(res => res.data)
  }
 
  async fetchShowEpisodes(
    theTvDbId: number,
    log = noop
  ): Promise<TheTvDbShowEpisode[]> {
    let episodes: TheTvDbShowEpisode[] = []
    let nextPageToLoad = 1;
    while (nextPageToLoad) {
      const response = await this.fetchEpisodePage(
        theTvDbId,
        nextPageToLoad,
        log
      )
      nextPageToLoad = response.links?.next;
      episodes = [ ...episodes, ...response.data ];
    }
    return episodes;
  }
 
  /**
   * Fetch the latest episodes.
   * Will return somewhere between 0 and numberOfEpisodes + 99 episodes
   */
  async fetchLatestShowEpisodes(
    theTvDbId: number,
    numberOfEpisodes: number,
    log = noop
  ) {
    const response = await this.fetchEpisodePage(
      theTvDbId,
      1,
      log
    )
 
    const lastPage = response.links?.last || 1;
 
    if (lastPage === 1) {
      return response.data
    } else if (lastPage === 2) {
      const result = await this.fetchEpisodePage(
        theTvDbId,
        2,
        log
      )
      return [...response.data, ...result.data]
    }
 
    let nextPageToLoad = lastPage;
    let episodes: TheTvDbShowEpisode[] = []
    while (episodes.length < numberOfEpisodes && nextPageToLoad) {
      const result = await this.fetchEpisodePage(
        theTvDbId,
        nextPageToLoad,
        log
      )
      episodes = [...result.data, ...episodes];
      nextPageToLoad = result.links.prev;
    }
 
    return episodes;
  }
 
  fetchLastUpdateShowsList(
    lastUpdate: number,
    log = noop
  ): Promise<TheTvDbUpdatedShowId[]> {
    return this.get(
      'https://api.thetvdb.com/updated/query?fromTime=' + lastUpdate,
      log
    )
      .then(handelHttpError)
      .then(res => res.json())
      .then(res => res.data)
      .then(data => ensureArray(data))
  }
 
  fetchEpisodeImage(episodeId: number, log = noop): Promise<Buffer> {
    return this.get('https://api.thetvdb.com/episodes/' + episodeId, log)
      .then(handelHttpError)
      .then(res => res.json())
      .then(res => res.data)
      .then((episode: TheTvDbEpisode) => episode.filename)
      .then(rejectIfNot(new NotFound()))
      .then(filename => this.fetchImage(filename, log))
  }
 
  fetchShowPoster(showId: number, log = noop): Promise<Buffer> {
    return this.get(
      `https://api.thetvdb.com/series/${showId}/images/query?keyType=poster`,
      log
    )
      .then(handelHttpError)
      .then(res => res.json())
      .then(res => res.data)
      .then(getHigestRating)
      .then(rejectIfNot(new NotFound()))
      .then(image => image.fileName)
      .then(filename => this.fetchImage(filename, log))
  }
 
  fetchShowFanart(showId: number, log = noop): Promise<Buffer> {
    return this.get(
      `https://api.thetvdb.com/series/${showId}/images/query?keyType=fanart`,
      log
    )
      .then(handelHttpError)
      .then(res => res.json())
      .then(res => res.data)
      .then(getHigestRating)
      .then(rejectIfNot(new NotFound()))
      .then(image => image.fileName)
      .then(filename => this.fetchImage(filename, log))
  }
 
  private fetchEpisodePage(theTvDbId: number, page: number, log = noop): Promise<TheTvDbShowEpisodePage> {
    return this.get(
      `https://api.thetvdb.com/series/${theTvDbId}/episodes?page=${page}`,
      log
    )
      .then(res => {
        // The tv db API has a bug where the next page can give a 404
        if (res.status === 404) {
          return {
            data: [],
            links: {} as any
          } as TheTvDbShowEpisodePage
        }
        handelHttpError(res)
        return res.json()
      })
      .then(res => {
        return {
          data: ensureArray(res.data),
          links: res.links
        }
      })
      .then(logWrapper(log, `Done, getting back`))
  }
 
  private fetchImage(filename: string, log: typeof noop): Promise<Buffer> {
    log(`Making request to: 'https://www.thetvdb.com/banners/${filename}'`)
    return this.fetch('https://www.thetvdb.com/banners/' + filename)
      .then(handelHttpError)
      .then(logWrapper(log, 'Parse the response as a buffer'))
      .then(response => response.buffer())
      .then(logWrapper(log, 'Done and done'))
  }
 
  private async get(
    url: string,
    log: typeof noop,
    timeout = this.options.timeout
  ): Promise<Response> {
    log('Making request to ' + url)
    const token = await this.token
    const controller = new AbortController()
    const timeoutId = setTimeout(() => controller.abort(), timeout)
 
    try {
      const result = await this.fetch(url, {
        method: 'GET',
        headers: { Authorization: 'Bearer ' + token },
        signal: controller.signal
      } as any) // The current type to not accept signal
      clearTimeout(timeoutId)
      log('We got a result from ' + url)
      return result
    } catch (error) {
      clearTimeout(timeoutId)
      if (error.name === 'AbortError') {
        log(`Did not recive any reposne within ${timeout} ms. url: ` + url)
        const nextTimeout = this.options.nextTimeout(timeout)
        if (!nextTimeout) {
          log(`Giving up. url: ` + url)
          throw new Timeout(`Timeout after ${timeout} ms for url: ${url}`)
        }
        return this.get(url, log, nextTimeout)
      }
      if (error) {
        log(
          `Could not get any respone. ${error.name} ${error.message}. url: ` +
            url
        )
      } else {
        log(`Could not get any respone. url: ` + url)
      }
      throw error
    }
  }
 
  private fetchToken(): Promise<string> {
    return this.fetch('https://api.thetvdb.com/login', {
      method: 'POST',
      body: JSON.stringify({
        apikey: this.apikey
      }),
      headers: { 'Content-Type': 'application/json' }
    })
      .then(handelHttpError)
      .then(res => res.json())
      .then(result => result.token)
  }
}
 
export function getHigestRating(images: TheTvDbShowImage[]): TheTvDbShowImage {
  return ensureArray(images).reduce((acc, image) => {
    if (image.ratingsInfo.average > acc.ratingsInfo.average) {
      return image
    } else {
      return acc
    }
  }, images[0])
}
 
export function handelHttpError(res: Response) {
  if (res.status === 404) {
    throw new NotFound()
  }
  if (!res.ok) {
    throw new Error('Unable to make the http request: ' + res.statusText)
  }
  return res
}
 
export function ensureArray<T = any>(data: T[]): T[] {
  if (Array.isArray(data)) {
    return data
  }
  return []
}
 
function rejectIfNot(error: Error) {
  return <T>(val: T): Promise<T> =>
    val ? Promise.resolve(val) : Promise.reject(error)
}