{"size": 3980, "ext": "js", "max_stars_repo_path": "src/Bookmark.js", "max_stars_repo_name": "dofy/utools-bookmark-anywhere", "max_stars_repo_stars_event_min_datetime": "2019-12-13T05:12:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-25T08:23:18.000Z", "max_issues_repo_path": "src/Bookmark.js", "max_issues_repo_name": "dofy/utools-bookmark-anywhere", "max_issues_repo_issues_event_min_datetime": "2021-06-10T11:04:53.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-10T11:04:53.000Z", "max_forks_repo_path": "src/Bookmark.js", "max_forks_repo_name": "dofy/utools-bookmark-anywhere", "max_forks_repo_forks_event_min_datetime": "2019-12-15T09:06:51.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-25T08:23:20.000Z"}
{"max_stars_count": 3, "max_issues_count": 1, "max_forks_count": 3, "avg_line_length": 29.0510948905, "max_line_length": 96, "alphanum_fraction": 0.5005025126}
const { readFileSync } = require('fs')
const iconv = require('iconv-lite')
const request = require('request')
const CHARSET = 'utf-8'

module.exports = {
  // 解析页面，获取书签信息
  get(url, callback) {
    // save bookmark first
    callback(null, {
      _id: `bmaw::${url}`,
      title: url,
      keywords: url,
      description: url,
      url,
      times: 0,
      search: url,
    })
    request(
      {
        url,
        gzip: true,
        method: 'GET',
        encoding: null,
        headers: {
          'User-Agent': 'Mozilla/5.0',
        },
      },
      (error, res, rawData) => {
        const { statusCode } = res
        const [contentType, flag, headerCharset] = res.headers['content-type']
          .split(/;|=/)
          .map((item) => item.trim().toLowerCase())

        if (error || statusCode >= 400) {
          return
        }

        // parse content
        let testString = rawData.toString()
        let charset = flag === 'charset' ? headerCharset : CHARSET

        // get charset
        let charsetReg1 = /<\s*meta[^>]+charset=['"](.*?)['"]/gi
        let charsetMatch1 = charsetReg1.exec(testString)
        let charsetReg2 = /<\s*meta[^>]+http-equiv=['"]content-type['"][^>]+?charset=([\w-]+)/gi
        let charsetMatch2 = charsetReg2.exec(testString)
        charset = charsetMatch1
          ? charsetMatch1[1].toLowerCase()
          : charsetMatch2
          ? charsetMatch2[1].toLowerCase()
          : charset

        if (charset !== CHARSET) {
          testString = iconv.decode(rawData, charset)
        }

        // get title and keywords
        let titleReg = /<\s*title[^>]*>(.*?)<\s*\/\s*title>/gi
        let keywordsReg = /<\s*meta[^>]+name=['"]keywords['"][^>]+content=['"](.*?)['"]/gi
        let descReg = /<\s*meta[^>]+name=['"]description['"][^>]+content=['"](.*?)['"]/gi

        let titleMatch = titleReg.exec(testString)
        let keywordsMatch = keywordsReg.exec(testString)
        let descMatch = descReg.exec(testString)

        let title = titleMatch ? titleMatch[1] : url
        let keywords = keywordsMatch ? keywordsMatch[1] : ''
        let description = (descMatch ? descMatch[1] : url) || url
        callback(null, {
          _id: `bmaw::${url}`,
          title,
          keywords,
          description,
          url,
          times: 0,
          search: [url, title, keywords, description].join(),
        })
      },
    )
  },
  // 创建数据项
  add(url, callback = null, alert = true) {
    utools.hideMainWindow()
    if (url && /^https?:\/\//i.test(url)) {
      this.get(url, (err, bookmark) => {
        if (err) {
          alert && utools.showNotification(err.message)
          callback && callback(false)
        } else {
          let oldData = utools.db.get(bookmark._id)
          if (oldData) {
            // * 兼容 0.1.2
            bookmark.times = oldData.times ? oldData.times : 0
            bookmark._rev = oldData._rev
          }
          utools.db.put(bookmark)
          alert && utools.showNotification('😁 Bookmark saved!')
          callback && callback(true)
        }
      })
    } else {
      alert && utools.showNotification('😫 There is no URL to save!')
      callback && callback(false)
    }
    utools.outPlugin()
  },
  // 导入
  import(path) {
    let linkMatch,
      count = 0,
      succ = 0,
      fail = 0,
      linkReg = /<\s*a[^>]+href=['"](.*?)['"]/gi,
      content = readFileSync(path, CHARSET)
    utools.showNotification(`🚀 Import is started...`)
    while ((linkMatch = linkReg.exec(content))) {
      count++
      this.add(
        linkMatch[1],
        (isOk) => {
          isOk ? succ++ : fail++
          if ((succ + fail) % 7 === 0) {
            utools.showNotification(`👍 ${succ} / 👎 ${fail} / 👊 ${count}`)
          }
          if (succ + fail === count) {
            utools.showNotification(
              `🎉 Import completed! (👍${succ}/👎${fail}/👊${count})`,
            )
          }
        },
        false,
      )
    }
  },
}
