ids.ts 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. import { request, RequestConfig } from './request'
  2. import { createHmac } from 'crypto'
  3. export interface IdsConfig {
  4. endpoint: string
  5. accessKeyId: string
  6. accessKeySecret: string
  7. }
  8. export enum IdsChannel {
  9. Csdn = 1,
  10. Wechat = 2,
  11. Zhihu = 3,
  12. Juejin = 4
  13. }
  14. export type IdsCrawlRule = 'fulldata' | 'extdata'
  15. export interface IdsArticle {
  16. author_id: string | number
  17. cover_url: string
  18. code: IdsChannel
  19. title: string
  20. author_name?: string
  21. sn_code: string
  22. original_url?: string
  23. source_address?: string
  24. is_headline?: 0 | 1
  25. label?: string
  26. published_at: Date
  27. body: string
  28. is_original?: 0 | 1
  29. external_read_num?: number
  30. external_see_num?: number
  31. external_like_num?: number
  32. external_comment_num?: number
  33. }
  34. export class Ids {
  35. config: IdsConfig
  36. constructor(config: IdsConfig) {
  37. this.config = config
  38. }
  39. private async request(config: RequestConfig) {
  40. const { endpoint, accessKeyId, accessKeySecret } = this.config
  41. config.baseURL = endpoint
  42. config.url = config.url || '/'
  43. const timestamp = Math.floor(Date.now() / 1000)
  44. const data = config.url.toLowerCase() + timestamp
  45. const signature = createHmac('sha256', accessKeySecret).update(data).digest('base64')
  46. config.headers = config.headers || {}
  47. config.headers['Authorization'] = `IDS-HMAC-SHA256 Credential=${accessKeyId}/${timestamp},Signature=${signature}`
  48. const res = await request(config)
  49. if (res.data.status != 1) {
  50. console.error(res.data)
  51. throw new Error(`[${res.data.status}] ${res.data.info}`)
  52. }
  53. return res.data
  54. }
  55. getCrawlAuthors(channel: IdsChannel) {
  56. return this.request({
  57. method: 'POST',
  58. url: '/api/ids/getCrawlAuthors',
  59. data: {
  60. code: channel
  61. }
  62. })
  63. }
  64. getCrawlArticleRules(params: { ids: string[]; channel: IdsChannel }) {
  65. const { ids, channel } = params
  66. return this.request({
  67. method: 'POST',
  68. url: '/api/ids/getCrawlArticleRules',
  69. data: {
  70. code: channel,
  71. sn_codes: ids
  72. }
  73. })
  74. }
  75. putArticle(data: IdsArticle, rule: IdsCrawlRule) {
  76. return this.request({
  77. method: 'POST',
  78. url: `/api/ids/putArticleData?crawl=${rule}`,
  79. data
  80. })
  81. }
  82. }