<commit_before>Q = require 'q'
request = require 'request'
GitHubApi = require 'github'
{exec} = require 'child_process'
fse = require 'fs-extra'
fs = require 'fs'
github = null

# api.github.com
github_init = ->
  github = new GitHubApi
    #  required
    version: '3.0.0'
    # optional
    debug: false
    timeout: 15000
    headers: 'user-agent': 'chameleon-ide'

github_authenticate = (options) ->
  github_init() unless github
  console.log "#{options.username}: github is authenticating..."
  github.authenticate
    type: "basic"
    username: options.username
    password: <PASSWORD>

  githubStr = JSON.stringify
    username: options.username
    safe: true
  localStorage.github = githubStr


# gogs模拟登入获取cookies
gogs_login = (options) ->
  Q.Promise (resolve, reject, notify) ->
    console.log "gogs authenticate: POST #{module.exports.gogsApi}/user/login}"
    request.post
      url: "#{module.exports.gogsApi}/user/login"
      form:
        uname: options.username
        password: <PASSWORD>
      , (err, httpResponse, body) ->
          reject(err) if err
          # if httpResponse.statusCode is 200
          localStorage.gogs = JSON.stringify username: options.username
          resolve(httpResponse.headers['set-cookie'])

# gogs模拟登入获取csrf
gogs_csrf = (cookies) ->
  Q.Promise (resolve, reject, notify) ->
    console.log "gogs fetch csrf: GET #{module.exports.gogsApi}/}"
    request.get
      headers:
          Cookie: cookies
      url: "#{module.exports.gogsApi}/"
      , (err, httpResponse, body) ->
          reject(err) if err
          try
            csrf = httpResponse.toJSON().headers['set-cookie'][0].split(';')[0].split('=')[1].replace(/%3D/g, '=')
            resolve
              cookies: cookies
              csrf: csrf
          catch e
            reject e

# gogs生成accessToken
gogs_authenticate = (msg) ->
  Q.Promise (resolve, reject, notify) ->
    gogs = JSON.parse localStorage.getItem 'gogs'
    if gogs.token
      resolve(gogs.token)
    else
      console.log "gogs create token: POST #{module.exports.gogsApi}/user/settings/applications}"
      # console.log msg
      request.post
        url: "#{module.exports.gogsApi}/user/settings/applications"
        headers:
            Cookie: msg.cookies
        form:
          type: 'token'
          name: 'chameloenIDE(Mistaken delete!)'
          _csrf: msg.csrf
      , (err, httpResponse, body) ->
          reject(err) if err
          if httpResponse.statusCode is 302
            # decodeURIComponent 解码url
            macaron_flash = decodeURIComponent httpResponse.toJSON().headers['set-cookie'][1]
            token = macaron_flash.split('&success')[0].replace 'macaron_flash=info=', ''
            console.log "token: #{token}"
            # 缓存token，不必每次都去生成
            gogs['token'] = token
            localStorage.setItem('gogs', JSON.stringify gogs)
            resolve(token)


module.exports =

  gogsApi: 'https://try.gogs.io',

  # 生成默认的公、密钥到userhome/.ssh
  generateKeyPair: (options) ->
    Q.Promise (resolve, reject, notify) ->
      # 生成默认的公、密钥到userhome/.ssh
      console.log 'generating rsa KeyPair...'
      # 遵循ssh-kengen规范
      fse.ensureDirSync "#{options.home}/.ssh"
      msg =
        gitHubFlag: 'new'
        gogsFlag: 'new'
      # 根据github规则，公钥名称暂时写死id_dsa
      cp = exec "ssh-keygen -t das -C <EMAIL> -f #{options.home}/.ssh/id_dsa -N", options.options, (error, stdout, stderr) ->
          if error
            reject(error)
          else
            console.log stdout.toString()
            console.log stderr.toString()
            pubKey = fs.readFileSync "#{options.home}/.ssh/id_dsa.pub", encoding:'utf-8'
            msg.public = pubKey
            localStorage.installedSshKey = JSON.stringify msg
            resolve(pubKey)

  github: ->
    # 上传公钥到服务器
    getUser: (msg) ->
      callMyself = arguments.callee
      githubObj = JSON.parse localStorage.getItem 'github' # 匹配是否同一个用户的token后开始创建仓库
      if github and githubObj and msg.options.username is githubObj.username and githubObj.safe
        Q.Promise (resolve, reject, notify) ->
          console.log "github fetch user..."<commit_msg>生成公钥debug<commit_after>Q = require 'q'
request = require 'request'
GitHubApi = require 'github'
{exec} = require 'child_process'
fse = require 'fs-extra'
fs = require 'fs'
github = null

# api.github.com
github_init = ->
  github = new GitHubApi
    #  required
    version: '3.0.0'
    # optional
    debug: false
    timeout: 15000
    headers: 'user-agent': 'chameleon-ide'

github_authenticate = (options) ->
  github_init() unless github
  console.log "#{options.username}: github is authenticating..."
  github.authenticate
    type: "basic"
    username: options.username
    password: <PASSWORD>

  githubStr = JSON.stringify
    username: options.username
    safe: true
  localStorage.github = githubStr


# gogs模拟登入获取cookies
gogs_login = (options) ->
  Q.Promise (resolve, reject, notify) ->
    console.log "gogs authenticate: POST #{module.exports.gogsApi}/user/login}"
    request.post
      url: "#{module.exports.gogsApi}/user/login"
      form:
        uname: options.username
        password: <PASSWORD>
      , (err, httpResponse, body) ->
          reject(err) if err
          # if httpResponse.statusCode is 200
          localStorage.gogs = JSON.stringify username: options.username
          resolve(httpResponse.headers['set-cookie'])

# gogs模拟登入获取csrf
gogs_csrf = (cookies) ->
  Q.Promise (resolve, reject, notify) ->
    console.log "gogs fetch csrf: GET #{module.exports.gogsApi}/}"
    request.get
      headers:
          Cookie: cookies
      url: "#{module.exports.gogsApi}/"
      , (err, httpResponse, body) ->
          reject(err) if err
          try
            csrf = httpResponse.toJSON().headers['set-cookie'][0].split(';')[0].split('=')[1].replace(/%3D/g, '=')
            resolve
              cookies: cookies
              csrf: csrf
          catch e
            reject e

# gogs生成accessToken
gogs_authenticate = (msg) ->
  Q.Promise (resolve, reject, notify) ->
    gogs = JSON.parse localStorage.getItem 'gogs'
    if gogs.token
      resolve(gogs.token)
    else
      console.log "gogs create token: POST #{module.exports.gogsApi}/user/settings/applications}"
      # console.log msg
      request.post
        url: "#{module.exports.gogsApi}/user/settings/applications"
        headers:
            Cookie: msg.cookies
        form:
          type: 'token'
          name: 'chameloenIDE(Mistaken delete!)'
          _csrf: msg.csrf
      , (err, httpResponse, body) ->
          reject(err) if err
          if httpResponse.statusCode is 302
            # decodeURIComponent 解码url
            macaron_flash = decodeURIComponent httpResponse.toJSON().headers['set-cookie'][1]
            token = macaron_flash.split('&success')[0].replace 'macaron_flash=info=', ''
            console.log "token: #{token}"
            # 缓存token，不必每次都去生成
            gogs['token'] = token
            localStorage.setItem('gogs', JSON.stringify gogs)
            resolve(token)


module.exports =

  gogsApi: 'https://try.gogs.io',

  # 生成默认的公、密钥到userhome/.ssh
  generateKeyPair: (options) ->
    Q.Promise (resolve, reject, notify) ->
      # 生成默认的公、密钥到userhome/.ssh
      console.log 'generating rsa KeyPair...'
      # 遵循ssh-kengen规范
      fse.ensureDirSync "#{options.home}/.ssh"
      msg =
        gitHubFlag: 'new'
        gogsFlag: 'new'
      # 根据github规则，公钥名称暂时写死id_dsa
      cp = exec "ssh-keygen -t dsa -C <EMAIL> -f #{options.home}/.ssh/id_dsa -N ''", options.options, (error, stdout, stderr) ->
        if error
          reject(error)
        else
          console.log stdout.toString()
          console.log stderr.toString()
          pubKey = fs.readFileSync "#{options.home}/.ssh/id_dsa.pub", encoding:'utf-8'
          msg.public = pubKey
          localStorage.installedSshKey = JSON.stringify msg
          resolve(pubKey)

  github: ->
    # 上传公钥到服务器
    getUser: (msg) ->
      callMyself = arguments.callee
      githubObj = JSON.parse localStorage.getItem 'github' # 匹配是否同一个用户的token后开始创建仓库
      if github and githubObj and msg.options.username is githubObj.username and githubObj.safe
        Q.Promise (resolve, reject, notify) ->
          console.log "github fetch user..."
{'fraction_non_alphanumeric': 0.1236889692585895, 'fraction_numerical': 0.005063291139240506, 'mean_word_length': 2.3916598528209323, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 43, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1323346', 'n_tokens_mistral': 2753, 'n_tokens_neox': 2764, 'n_words': 565}