File size: 5,722 Bytes
cb3fcd8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import puppeteer from 'puppeteer';
import tough from 'tough-cookie';
import iconv from 'iconv-lite';
import {load} from 'cheerio';
import path from 'path';
import fs from 'fs-extra';
import dotenv from 'dotenv';
import { execSync } from 'child_process';
import {join} from 'path';
import {jar, chineseToUnicode, downloadFile, gb2312UrlEncode, get, post, parseCookies, reset_cookie_jar} from './utils.js';

dotenv.config();

const host = 'https://mmis.hkpl.gov.hk'
async function get_list(page) {
  const url = `${host}/search-result?p_p_id=search_WAR_mmisportalportlet&p_p_lifecycle=0&p_p_state=normal&_search_WAR_mmisportalportlet_keywords=%E5%A4%A7%E5%85%AC%E5%A0%B1&_search_WAR_mmisportalportlet_hsf=%E5%A4%A7%E5%85%AC%E5%A0%B1&p_r_p_-1078056564_actual_q=%28%20all_dc.title%3A%28%22%E5%A4%A7%E5%85%AC%E5%A0%B1%22%29%29%20AND+%28%20verbatim_dc.collection%3A%28%22Old%5C%20HK%5C%20Newspapers%22%29%29&p_r_p_-1078056564_sort_field=dc.publicationdate_bsort&_search_WAR_mmisportalportlet_mode=Advanced&p_r_p_-1078056564_curr_page=${page}&_search_WAR_mmisportalportlet__advancedsearch_WAR_mmisportalportlet_formDate=1389840730864&p_r_p_-1078056564_new_search=false&p_r_p_-1078056564_sort_order=desc&_search_WAR_mmisportalportlet_jspPage=%2Fjsp%2Fsearch%2Fcnsc05.jsp`;
  let html = "";
  const dir = `./html/list`;
  const f = join(dir, page + ".html");
  if (
    await fs.exists(f) &&
    (await fs
      .readFile(f))
      .toString()
      .indexOf("The system is busy. Please retry later") != -1
  ) {
    await fs.unlink(f);
  }
  if (await fs.exists(f)) {
    console.log("exists", f);
    html = (await fs.readFile(f)).toString();
  } else {
    while (true) {
      const { data } = await get(url);
      if (data.indexOf("The system is busy. Please retry later") != -1) {
        continue;
      }
      html = data;
      const a = html.indexOf("<body");
      const b = html.indexOf("</body>");
      html = html.substring(a, b) + "</body>";
      const links = load(html)(".result-title a");
      await fs.ensureDir(dir);
      if (!links.length) {
        return [];
      }
      await fs.writeFile(f, html);
      break;
    }
  }

  const links = load(html)(".result-title a");
  const res = [];
  for (const link of links) {
    res.push({
      href: link.attribs.href,
      text: link.children[0].data,
    });
  }
  return res;
}

async function crawl_by_page(page) {
  const links = await get_list(page);
  for (const link of links) {
    const date_str = link.text.split(" ")[1];
    let [year, month, day] = date_str.split("-");
    month = parseInt(month);
    day = parseInt(day);
    year = parseInt(year);
    const dir = join(`./html/newspaper/${year}/${month}/${day}`);
    const f = join(dir, "index.html");
    let detail_html = "";
    if ((await fs.exists(f)) && (await fs.readFile(f)).toString().indexOf('The system is busy. Please retry later') != -1) {
      await fs.unlink(f);
    }
    if (await fs.exists(f)) {
      console.log("exists", f);
      detail_html = (await fs.readFile(f)).toString();
    } else {
      await fs.ensureDir(dir);
      while (true) {
        const { data: html } = await get(`${host}${link.href}`);
        if (html.indexOf("The system is busy. Please retry later") != -1) continue;
        await fs.writeFile(f, html);
        detail_html = html;
        break;
      }
    }

    const key = 'htmlURL="';
    const pivot = detail_html.indexOf(key);
    const viewer_url = `${host}${detail_html.substring(
      pivot + key.length,
      detail_html.indexOf('"', pivot + key.length)
    )}`;
    const key2 = "initPageLinks(null,";
    const pivot2 = detail_html.indexOf(key2);
    const total_page = parseInt(
      detail_html.substring(
        pivot2 + key2.length,
        detail_html.indexOf(",", pivot2 + key2.length)
      )
    );

    const search_params = new URLSearchParams("?" + viewer_url.split("?")[1]);

    const month_pad_start = month.toString().padStart(2, "0");
    const day_pad_start = day.toString().padStart(2, "0");
    for (let i = 1; i <= total_page; ++i) {
      // console.log("download img", year, month, day, i, "/", total_page);
      const img_path = join(dir, i + ".png");
      if (await fs.exists(img_path)) {
        if ((await fs.readFile(img_path)).toString().indexOf('The system is busy. Please retry later') != -1) {
          await fs.unlink(img_path);
        } else {
          // console.log("skip");
          continue;
        }
      }

      // const encToken = search_params.get("encToken");
      const encToken =
      '...';
      const img_url =
        `https://mmis.hkpl.gov.hk/ebook/viewer?resource=page` +
        `&item=${search_params.get("item")}` +
        `&type=` +
        `&ref=%2FMULTI_IMAGE_INDEX%2F${
          month_pad_start + day_pad_start
        }%2FNPTKP${
          year.toString() + month_pad_start + day_pad_start
        }%2Fimage%2FNPTKP${
          year.toString() + month_pad_start + day_pad_start
        }_${i.toString().padStart(2, "0")}.png` +
        `&encToken=${encodeURIComponent(encToken)}`;
      // console.log(img_url);
      await downloadFile(img_url, img_path, Infinity);
    }
    // const {data: viewer_html} = await get(viewer_url);
    // console.log(viewer_html);
    // return;
  }
}


(async () => {
  const pages = Math.floor(16865 / 10);
  const arr = (new Array(pages)).fill(0).map((_, i) => i+1);//.sort(() => Math.random() > 0.5 ? 1 : -1);
  /*
  for (let i = 1; i <= pages; ++i) {
    // console.log(i + "/" + pages);
    crawl_by_page(i);
  }
  */
  await Promise.all[
    new Array(10).fill(0).map(async (i) => {
      while (arr.length) {
        console.log(arr.length);
        await crawl_by_page(arr.pop());
      }
    })
  ];
})();