"""
@author: pysta feat by AsVow
@file: req2js.py
@createTime: 2020-05-01
@updateTime: 2021-12-28
@description: 根据Surge | Thor | Qx | 网球 请求内容生成相应的 js 请求脚本 兼容Qx | Surge | Loon

Surge: 支持 zip 导出，由于其 cURL 导出比较奇葩不支持
Thor: 支持 har 及 CURL 导出
Qx: 支持文件夹导出
网球: 支持 cURL 导出
"""

import zipfile
import json
import appex
import clipboard
import console
import argparse
import shlex
from urllib3.filepost import encode_multipart_formdata as emf

def parse_curl(curl):
    parser = argparse.ArgumentParser()
    parser.add_argument('command')
    parser.add_argument('url')
    parser.add_argument('-d', '--data')
    parser.add_argument('--data-raw')
    parser.add_argument('--data-binary')
    parser.add_argument('-X', default='GET')
    parser.add_argument('-H', '--header', action='append', default=[])
    parser.add_argument('-L', action="store_true")
    parser.add_argument('--compressed', action='store_true')
    parser.add_argument('-k', '--insecure', action='store_true')
    
    tokens = shlex.split(curl)
    parsed_args = parser.parse_args(tokens)
    body = parsed_args.data or parsed_args.data_raw or parsed_args.data_binary or ''
    method = parsed_args.X.lower()
    url = parsed_args.url
    headers = {k:v.strip() for k,v in [i.split(':', 1) for i in parsed_args.header]}
    
    return url, body, headers, method

def parse(path): 
  
  def parse_har():
    with open(path, 'r', encoding='utf-8') as f:
      d = json.load(f)['log']['entries'][
    0]['request']
      
    url = d['url']
    headers = {i['name']: i['value'] for i in d['headers']}
    params = d.get('postData',{}).get('params', '')
    if params: # multipart_formdata
      _ = [(i['name'], i.get('value', '')) for i in params]
      content,headers['Content-Type'] = emf(_)
      body = str(content, encoding='utf-8')
    else:
      body = d.get('postData', {}).get('text', '')    
    method = d['method'].lower()
    
    return url, body, headers, method
    
  def parse_qx():
  
    with open(f'{path}/0/basic') as f:
      url = f.read()
    with open(f'{path}/0/request_body') as f:
      body = f.read()
    with open(f'{path}/0/request_headers') as f:
      temp = f.read()
      method = temp.split()[0].lower()
      headers = {k:v for k, v in [i.split(': ',1) for i in temp.split('\n')[1:] if i]}
    
    return url, body, headers, method
  
  def parse_surge():
  
    with zipfile.ZipFile(path, 'r') as z:
      with z.open('model.json') as f:
        d = json.load(f)
      if 'request.dump' in z.namelist():
        with z.open('request.dump') as f:
          d['reqBody'] = f.read().decode('utf-8')
    
    url = d['URL']
    body = d.get('reqBody', '')
    method = d['method'].lower()
    headers = {k:v for k, v in [i.split(': ',1) for i in d['requestHeader'].split('\r\n')[1:] if i]}
    
    return url, body, headers, method
  
  if path.endswith('.har'):
    return parse_har()
  elif path.endswith('.zip'):
    return parse_surge()
  else:
    return parse_qx()
    
def main():
  path = appex.get_file_path()
  if path:
    url, body, headers, method = parse(path)
  else:
    curl = appex.get_text()
    url, body, headers, method = parse_curl(curl)
  
  js = f'''
const $ = API("AsVow");
var info = "";
!(async () => {{
  await AsVow();
}})().finally(() => {{
  $.notify($.name, "", info);
  $.done();
}});
function AsVow() {{
  const url = {json.dumps(url)};
  const body = {json.dumps(body)};
  const headers = {json.dumps(headers, indent=6)};
  const request = {{
      url: url,
      headers: headers,
      body: body
  }};
  return new Promise(resolve => {{
    $.http.{method}(request)
      .then((resp) => {{
        const data = resp.body;
        info += "请求成功\\n";
        info += data;
      }})
      .catch((err) => {{
        info += "请求失败\\n";
        info += $.toStr(err);
      }})
      .finally(() => {{
        resolve();
      }});
  }});
}}
'''
  js=js+'''
// prettier-ignore
/*********************************** API *************************************/
function ENV(){const e="undefined"!=typeof $task,t="undefined"!=typeof $loon;return{isQX:e,isLoon:t,isSurge:"undefined"!=typeof $httpClient&&!t,isRequest:"undefined"!=typeof $request,isScriptable:"undefined"!=typeof importModule}}function HTTP(e={baseURL:""}){const{isQX:t,isLoon:s,isSurge:n,isScriptable:o}=ENV(),i=/https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)/;const r={};return["GET","POST","PUT","DELETE","HEAD","OPTIONS","PATCH"].forEach(u=>r[u.toLowerCase()]=(r=>(function(r,u){u="string"==typeof u?{url:u}:u;const a=e.baseURL;a&&!i.test(u.url||"")&&(u.url=a?a+u.url:u.url),u&&u.body&&u.headers&&!u.headers["Content-Type"]&&(u.headers["Content-Type"]="application/x-www-form-urlencoded");const h=(u={...e,...u}).timeout,c={...{onRequest:()=>{},onResponse:e=>e,onTimeout:()=>{}},...u.events};let l,f;if(c.onRequest(r,u),t)l=$task.fetch({method:r,...u});else if(s||n)l=new Promise((e,t)=>{$httpClient[r.toLowerCase()](u,(s,n,o)=>{s?t(s):e({statusCode:n.status||n.statusCode,headers:n.headers,body:o})})});else if(o){const e=new Request(u.url);e.method=r,e.headers=u.headers,e.body=u.body,l=new Promise((t,s)=>{e.loadString().then(s=>{t({statusCode:e.response.statusCode,headers:e.response.headers,body:s})}).catch(e=>s(e))})}const d=h?new Promise((e,t)=>{f=setTimeout(()=>(c.onTimeout(),t(`${r} URL: ${u.url} exceeds the timeout ${h} ms`)),h)}):null;return(d?Promise.race([d,l]).then(e=>(clearTimeout(f),e)):l).then(e=>c.onResponse(e))})(u,r))),r}function API(e="untitled",t=!1){const{isQX:s,isLoon:n,isSurge:o,isScriptable:i}=ENV();return new class{constructor(e,t){this.name=e,this.debug=t,this.http=HTTP(),this.env=ENV(),this.startTime=(new Date).getTime(),console.log(`🔔${e}, 开始!`),this.initCache();Promise.prototype.delay=function(e){return this.then(function(t){return((e,t)=>new Promise(function(s){setTimeout(s.bind(null,t),e)}))(e,t)})}}initCache(){s&&(this.cache=this.toObj($prefs.valueForKey(this.name)||"{}")),(n||o)&&(this.cache=this.toObj($persistentStore.read(this.name)||"{}"))}persistCache(){const e=this.toStr(this.cache);s&&$prefs.setValueForKey(e,this.name),(n||o)&&$persistentStore.write(e,this.name)}write(e,t){if(this.log(`SET ${t}`),-1!==t.indexOf("#")){if(t=t.substr(1),o||n)return $persistentStore.write(e,t);if(s)return $prefs.setValueForKey(e,t)}else this.cache[t]=e;this.persistCache()}read(e){return this.log(`READ ${e}`),-1===e.indexOf("#")?this.cache[e]:(e=e.substr(1),o||n?$persistentStore.read(e):s?$prefs.valueForKey(e):void 0)}delete(e){if(this.log(`DELETE ${e}`),-1!==e.indexOf("#")){if(e=e.substr(1),o||n)return $persistentStore.write(null,e);if(s)return $prefs.removeValueForKey(e)}else delete this.cache[e];this.persistCache()}notify(e,t="",r="",u={}){const a=u["open-url"],h=u["media-url"];if(r=r.replace(/^(?=\\n)$|^\s*|\s*$|\\n\\n+/gm,""),!this.isMute){if(s&&$notify(e,t,r,u),o&&$notification.post(e,t,r+`${h?"\\n多媒体:"+h:""}`,{url:a}),n){let s={};a&&(s.openUrl=a),h&&(s.mediaUrl=h),"{}"===this.toStr(s)?$notification.post(e,t,r):$notification.post(e,t,r,s)}if(i){const s=r+(a?`\\n点击跳转: ${a}`:"")+(h?`\\n多媒体: ${h}`:"");console.log(`${e}\\n${t}\\n${s}\\n\\n`)}}if(!this.isMuteLog){let s=["","==============📣系统通知📣=============="];s.push(e),t&&s.push(t),r&&s.push(r),console.log(s.join("\\n"))}}log(e){this.debug&&console.log(`[${this.name}] LOG:\\n${this.toStr(e)}`)}info(e){console.log(`[${this.name}] INFO:\\n${this.toStr(e)}`)}error(e){console.log(`[${this.name}] ERROR:\\n${this.toStr(e)}`)}wait(e){return new Promise(t=>setTimeout(t,e))}done(e={}){const t=((new Date).getTime()-this.startTime)/1e3;console.log(`🔔${this.name}, 结束! 🕛 ${t} 秒`),$done(e)}toObj(e){if("object"==typeof e||e instanceof Object)return e;try{return JSON.parse(e)}catch(t){return e}}toStr(e){if("string"==typeof e||e instanceof String)return e;try{return JSON.stringify(e)}catch(t){return e}}}(e,t)}
/*****************************************************************************/
'''
  print(js)
  clipboard.set(js)
  console.hud_alert('Copyed!')
  
if __name__ == '__main__':
  if appex.is_running_extension():
    main()
  else:
    print('请设置为 Share Extension 脚本后使用。')