自動化打包腳本實(shí)現(xiàn)上傳蒲公英通知釘釘群

  • 創(chuàng)建task 任務(wù)
//打包測試環(huán)境apk 上傳蒲公英 發(fā)送郵件功能使用蒲公英自帶的郵件功能
task packageDingTalk {
    println "*************** upload finish ***************"
    def apkDir = new File("./app/build/outputs/apk/debug")
    if (apkDir.exists() && apkDir.isDirectory()) {
        apkDir.deleteDir()
    }

    dependsOn("assembleDebug")

    doLast {
        uploadApk("./app/build/outputs/apk/debug", "你的蒲公英apiKey", "123321")
    }
}

上面執(zhí)行任務(wù)packageDingTalk晓殊,然后構(gòu)建apk任務(wù)

  • 上傳apk 到蒲公英
/**
 * 上傳apk到蒲公英
 */
def uploadApk(def path, def apiKey, def pwd) {
    //查找上傳的apk文件前联,這里需要換成自己apk路徑
    println "*************** start upload file ***************"

    def apkDir = new File(path)
    if (!apkDir.exists()) {
        throw new RuntimeException("apk output path not exists!")
    }

    def apk = null
    for (int i = apkDir.listFiles().length - 1; i >= 0; i--) {
        File file = apkDir.listFiles()[i]
        if (file.name.endsWith(".apk")) {
            apk = file
            break
        }
    }
    if (apk == null) {
        throw new RuntimeException("apk file not exists!")
    }

    println "*************** start upload file ***************"

    def twoHyphens = "--"
    def boundary = "*********"
    def end = "\r\n"

    //模擬表單上傳 multipart/form-data
    def conn = new URL("https://www.pgyer.com/apiv2/app/upload").openConnection()
    conn.setRequestMethod('POST')
    conn.setRequestProperty("Connection", "Keep-Alive")
    conn.setRequestProperty("Charset", "UTF-8")
    conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary)
    conn.setDoInput(true)
    conn.setDoOutput(true)
    //添加參數(shù):_api_key
    def sb = new StringBuilder()
    sb.append(twoHyphens).append(boundary).append(end)
    sb.append("Content-Disposition: form-data; name=_api_key")
    sb.append(end).append(end)
    sb.append(apiKey).append(end)


//    def desc = "${proc.in.text}"
    //添加參數(shù):buildUpdateDescription 更新日志蒲祈,取值gradle.properties中的 BUILD_NOTES
    sb.append(twoHyphens).append(boundary).append(end)
    sb.append("Content-Disposition: form-data; name=buildUpdateDescription")
    sb.append(end).append(end)
    sb.append("This is Test").append(end)
    //安裝方式帆啃,密碼安裝
    sb.append(twoHyphens).append(boundary).append(end)
    sb.append("Content-Disposition: form-data; name=buildInstallType")
    sb.append(end).append(end)
    sb.append("2").append(end)
    //安裝密碼
    sb.append(twoHyphens).append(boundary).append(end)
    sb.append("Content-Disposition: form-data; name=buildPassword")
    sb.append(end).append(end)
    sb.append(pwd).append(end)

    //添加參數(shù)file: 需要上傳的apk文件
    sb.append(twoHyphens).append(boundary).append(end)
    sb.append("Content-Disposition: form-data; name=file;filename=").append(apk.getName())
    sb.append(end).append(end)


    def dos = new DataOutputStream(conn.getOutputStream())
    dos.writeBytes(sb.toString())
    dos.flush()
    sb.delete(0, sb.length())

    def fis = new FileInputStream(apk)
    byte[] bf = new byte[8192]
    int len
    while ((len = fis.read(bf)) != -1) {
        dos.write(bf, 0, len)
    }
    sb.append(end)
    sb.append(twoHyphens).append(boundary).append(end)
    dos.writeBytes(sb.toString())

    dos.flush()
    fis.close()
    dos.close()
    conn.connect()

    def text = conn.getContent().text
    def resp = new JsonSlurper().parseText(text)

    println text
    println "*************** upload finish ***************"

    if (resp.code != 0) {
        throw new RuntimeException(resp.message)
    }
    println resp
//    //瀏覽器中打開短連接
//    def url = "https://www.pgyer.com/" + resp.data.buildShortcutUrl
//    exec {
//        commandLine "bash", "start", url
//    }

    ///sendMsgToDing(resp.data, apiKey, pwd)
    sendMsgToDing(resp.data)

}

根據(jù)蒲公英提供文檔進(jìn)行apk 上傳

  • 發(fā)送通知到釘釘群
def sendMsgToDing(def data) {
    def conn = new URL("https://oapi.dingtalk.com/robot/send?access_token=4749345f6783568cab3b3700cb4728df9bdf9e81358137bbf2e197605f04aeaf").openConnection()
    conn.setRequestMethod('POST')
    conn.setRequestProperty("Connection", "Keep-Alive")
    conn.setRequestProperty("Content-type", "application/json;charset=UTF-8")
    conn.setConnectTimeout(30000)
    conn.setReadTimeout(30000)
    conn.setDoInput(true)
    conn.setDoOutput(true)
    def dos = new DataOutputStream(conn.getOutputStream())

    def downloadUrl = "https://www.pgyer.com/" + data.buildShortcutUrl
    def qrCodeUrl = "![](" + data.buildQRCodeURL + ")"
    def detailLink = "[項(xiàng)目地址](${11111})"
    def _title = "蒲公英機(jī)器人"
    def _content = new StringBuffer()
    _content.append("\n\n###Android 測試包構(gòu)建成功")
    _content.append("\n\n構(gòu)建版本:1.0")
    _content.append("\n\n構(gòu)建類型:dev")
    _content.append("\n\n下載地址:" + downloadUrl)
    _content.append("\n\n" + qrCodeUrl)
    _content.append("\n\n構(gòu)建用戶:桂雁彬")
    _content.append("\n\n構(gòu)建時間:" + getNowTime())
    _content.append("\n\n查看詳情:" + detailLink)
    def json = new groovy.json.JsonBuilder()
    json {
        msgtype "markdown"
        markdown {
            title _title
            text _content.toString()
        }
        at {
            atMobiles([])
            isAtAll false
        }
    }

    println(json)
    dos.writeBytes(json.toString())
    def input = new BufferedReader(new InputStreamReader(conn.getInputStream()))
    String line = ""
    String result = ""
    while ((line = input.readLine()) != null) {
        result += line
    }
    dos.flush()
    dos.close()
    input.close()
    conn.connect()
    println(result)

    println("*************** 釘釘消息已發(fā)送 ***************")
}

執(zhí)行任務(wù)

./gradlew packageDingTalk

最終釘釘群會有通知


image.png

完成代碼:

import groovy.json.JsonSlurper
import groovy.json.JsonOutput

import java.text.SimpleDateFormat

class ContentModel{
    String text
    String title
    String picUrl
    String messageUrl
}
/**
 * 上傳apk到蒲公英
 */
def uploadApk(def path, def apiKey, def pwd) {
    //查找上傳的apk文件,這里需要換成自己apk路徑
    println "*************** start upload file ***************"

    def apkDir = new File(path)
    if (!apkDir.exists()) {
        throw new RuntimeException("apk output path not exists!")
    }

    def apk = null
    for (int i = apkDir.listFiles().length - 1; i >= 0; i--) {
        File file = apkDir.listFiles()[i]
        if (file.name.endsWith(".apk")) {
            apk = file
            break
        }
    }
    if (apk == null) {
        throw new RuntimeException("apk file not exists!")
    }

    println "*************** start upload file ***************"

    def twoHyphens = "--"
    def boundary = "*********"
    def end = "\r\n"

    //模擬表單上傳 multipart/form-data
    def conn = new URL("https://www.pgyer.com/apiv2/app/upload").openConnection()
    conn.setRequestMethod('POST')
    conn.setRequestProperty("Connection", "Keep-Alive")
    conn.setRequestProperty("Charset", "UTF-8")
    conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary)
    conn.setDoInput(true)
    conn.setDoOutput(true)
    //添加參數(shù):_api_key
    def sb = new StringBuilder()
    sb.append(twoHyphens).append(boundary).append(end)
    sb.append("Content-Disposition: form-data; name=_api_key")
    sb.append(end).append(end)
    sb.append(apiKey).append(end)


//    def desc = "${proc.in.text}"
    //添加參數(shù):buildUpdateDescription 更新日志摊唇,取值gradle.properties中的 BUILD_NOTES
    sb.append(twoHyphens).append(boundary).append(end)
    sb.append("Content-Disposition: form-data; name=buildUpdateDescription")
    sb.append(end).append(end)
    sb.append("This is Test").append(end)
    //安裝方式狈涮,密碼安裝
    sb.append(twoHyphens).append(boundary).append(end)
    sb.append("Content-Disposition: form-data; name=buildInstallType")
    sb.append(end).append(end)
    sb.append("2").append(end)
    //安裝密碼
    sb.append(twoHyphens).append(boundary).append(end)
    sb.append("Content-Disposition: form-data; name=buildPassword")
    sb.append(end).append(end)
    sb.append(pwd).append(end)

    //添加參數(shù)file: 需要上傳的apk文件
    sb.append(twoHyphens).append(boundary).append(end)
    sb.append("Content-Disposition: form-data; name=file;filename=").append(apk.getName())
    sb.append(end).append(end)



    def dos = new DataOutputStream(conn.getOutputStream())
    dos.writeBytes(sb.toString())
    dos.flush()
    sb.delete(0, sb.length())

    def fis = new FileInputStream(apk)
    byte[] bf = new byte[8192]
    int len
    while ((len = fis.read(bf)) != -1) {
        dos.write(bf, 0, len)
    }
    sb.append(end)
    sb.append(twoHyphens).append(boundary).append(end)
    dos.writeBytes(sb.toString())

    dos.flush()
    fis.close()
    dos.close()
    conn.connect()

    def text = conn.getContent().text
    def resp = new JsonSlurper().parseText(text)

    println text
    println "*************** upload finish ***************"

    if (resp.code != 0) {
        throw new RuntimeException(resp.message)
    }
    println resp
//    //瀏覽器中打開短連接
//    def url = "https://www.pgyer.com/" + resp.data.buildShortcutUrl
//    exec {
//        commandLine "bash", "start", url
//    }

    ///sendMsgToDing(resp.data, apiKey, pwd)
    sendMsgToDing(resp.data)

}

//打包測試環(huán)境apk 上傳蒲公英 發(fā)送郵件功能使用蒲公英自帶的郵件功能
task packageDingTalk {
    println "*************** upload finish ***************"
    def apkDir = new File("./app/build/outputs/apk/debug")
    if(apkDir.exists() && apkDir.isDirectory()){
        apkDir.deleteDir()
    }

    dependsOn("assembleDebug")
    println "*************** upload 2222 ***************"

    doLast {
        println "*************** upload aaa ***************"

        uploadApk("./app/build/outputs/apk/debug","6f5973ca9c2e2a690b5c14a5f7d3cabf", "123321")
    }
}

task packageReleaseDingTalk {
    def apkDir = new File("./release")
    if(apkDir.exists() && apkDir.isDirectory()){
        apkDir.deleteDir()
    }
    dependsOn("assembleRelease")

    doLast {
        uploadApk("./release","6f5973ca9c2e2a690b5c14a5f7d3cabf", "123321")
    }
}



def sendMsgToDing(def data, def apiKey, def pwd){

    println "*************** upload finish ***************apiKey:"+apiKey+"pwd:::"+pwd

    def conn = new URL("https://oapi.dingtalk.com/robot/send?access_token=4749345f6783568cab3b3700cb4728df9bdf9e81358137bbf2e197605f04aeaf").openConnection()
    conn.setRequestMethod('POST')
    conn.setRequestProperty("Connection", "Keep-Alive")
    conn.setRequestProperty("Content-type", "application/json;charset=UTF-8")
    conn.setConnectTimeout(30000)
    conn.setReadTimeout(30000)
    conn.setDoInput(true)
    conn.setDoOutput(true)
    def dos = new DataOutputStream(conn.getOutputStream())
    HashMap<String,Object> map = new HashMap<>()
    map.put("msgtype", "link")
    ContentModel contentModel = new ContentModel()
    def command = """git log  -3  --pretty=format:'%s' --abbrev-commit"""http:// Create the String
    def proc = command.execute()                 // Call *execute* on the string
    proc.waitFor()                               // Wait for the command to finish
// Obtain status and output
    println "return code: ${ proc.exitValue()}"
    println "stderr: ${proc.err.text}"
    def k = proc.in.text.replaceAll("'","").replaceAll("\n",";")
    println "stdout: ${k}" // *out* from the external program is *in* for groovy
    contentModel.text = k
    contentModel.title= "蒲公英機(jī)器人"
    contentModel.picUrl = data.buildQRCodeURL
    contentModel.messageUrl= "https://www.pgyer.com/apiv2/app/install?_api_key=" + apiKey + "&buildKey="+data.buildKey+"&buildPassword="+pwd
    map.put("link",contentModel)
    def json = JsonOutput.toJson(map)
    println(json)
    dos.writeBytes(json)
    def input = new BufferedReader(new InputStreamReader(conn.getInputStream()))
    String line =""
    String result=""
    while ((line = input.readLine()) != null) {
        result +=  line
    }
    dos.flush()
    dos.close()
    input.close()
    conn.connect()
    println(result)

}



def sendMsgToDing(def data) {
    def conn = new URL("https://oapi.dingtalk.com/robot/send?access_token=4749345f6783568cab3b3700cb4728df9bdf9e81358137bbf2e197605f04aeaf").openConnection()
    conn.setRequestMethod('POST')
    conn.setRequestProperty("Connection", "Keep-Alive")
    conn.setRequestProperty("Content-type", "application/json;charset=UTF-8")
    conn.setConnectTimeout(30000)
    conn.setReadTimeout(30000)
    conn.setDoInput(true)
    conn.setDoOutput(true)
    def dos = new DataOutputStream(conn.getOutputStream())

    def downloadUrl = "https://www.pgyer.com/" + data.buildShortcutUrl
    def qrCodeUrl = "![](" + data.buildQRCodeURL + ")"
    def detailLink = "[項(xiàng)目地址](${11111})"

    def _title = "蒲公英機(jī)器人"
    def _content = new StringBuffer()
    _content.append("\n\n###Android 測試包構(gòu)建成功")
    _content.append("\n\n構(gòu)建版本:1.0")
    _content.append("\n\n構(gòu)建類型:dev")
    _content.append("\n\n下載地址:" + downloadUrl)
    _content.append("\n\n" + qrCodeUrl)
    _content.append("\n\n構(gòu)建用戶:桂雁彬")
    _content.append("\n\n構(gòu)建時間:" + getNowTime())
    _content.append("\n\n查看詳情:" + detailLink)
    def json = new groovy.json.JsonBuilder()
    json {
        msgtype "markdown"
        markdown {
            title _title
            text _content.toString()
        }
        at {
            atMobiles([])
            isAtAll false
        }
    }

    println(json)
    dos.writeBytes(json.toString())
    def input = new BufferedReader(new InputStreamReader(conn.getInputStream()))
    String line = ""
    String result = ""
    while ((line = input.readLine()) != null) {
        result += line
    }
    dos.flush()
    dos.close()
    input.close()
    conn.connect()
    println(result)

    println("*************** 釘釘消息已發(fā)送 ***************")
}


//獲取當(dāng)前時間
def getNowTime() {
    def str = "";
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    Calendar lastDate = Calendar.getInstance();
    str = sdf.format(lastDate.getTime());
    return str;
}
```http://www.reibang.com/p/82c4ed377385
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末狐胎,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子歌馍,更是在濱河造成了極大的恐慌握巢,老刑警劉巖,帶你破解...
    沈念sama閱讀 219,427評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件骆姐,死亡現(xiàn)場離奇詭異,居然都是意外死亡捏题,警方通過查閱死者的電腦和手機(jī)玻褪,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,551評論 3 395
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來公荧,“玉大人带射,你說我怎么就攤上這事⊙” “怎么了窟社?”我有些...
    開封第一講書人閱讀 165,747評論 0 356
  • 文/不壞的土叔 我叫張陵,是天一觀的道長绪钥。 經(jīng)常有香客問我灿里,道長,這世上最難降的妖魔是什么程腹? 我笑而不...
    開封第一講書人閱讀 58,939評論 1 295
  • 正文 為了忘掉前任匣吊,我火速辦了婚禮,結(jié)果婚禮上寸潦,老公的妹妹穿的比我還像新娘色鸳。我一直安慰自己,他們只是感情好见转,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,955評論 6 392
  • 文/花漫 我一把揭開白布命雀。 她就那樣靜靜地躺著,像睡著了一般斩箫。 火紅的嫁衣襯著肌膚如雪吏砂。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,737評論 1 305
  • 那天乘客,我揣著相機(jī)與錄音赊抖,去河邊找鬼。 笑死寨典,一個胖子當(dāng)著我的面吹牛氛雪,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播耸成,決...
    沈念sama閱讀 40,448評論 3 420
  • 文/蒼蘭香墨 我猛地睜開眼报亩,長吁一口氣:“原來是場噩夢啊……” “哼浴鸿!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起弦追,我...
    開封第一講書人閱讀 39,352評論 0 276
  • 序言:老撾萬榮一對情侶失蹤岳链,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后劲件,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體掸哑,經(jīng)...
    沈念sama閱讀 45,834評論 1 317
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,992評論 3 338
  • 正文 我和宋清朗相戀三年零远,在試婚紗的時候發(fā)現(xiàn)自己被綠了苗分。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,133評論 1 351
  • 序言:一個原本活蹦亂跳的男人離奇死亡牵辣,死狀恐怖摔癣,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情纬向,我是刑警寧澤择浊,帶...
    沈念sama閱讀 35,815評論 5 346
  • 正文 年R本政府宣布,位于F島的核電站逾条,受9級特大地震影響琢岩,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜师脂,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,477評論 3 331
  • 文/蒙蒙 一粘捎、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧危彩,春花似錦攒磨、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,022評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至谒府,卻和暖如春拼坎,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背完疫。 一陣腳步聲響...
    開封第一講書人閱讀 33,147評論 1 272
  • 我被黑心中介騙來泰國打工泰鸡, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人壳鹤。 一個月前我還...
    沈念sama閱讀 48,398評論 3 373
  • 正文 我出身青樓盛龄,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子余舶,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,077評論 2 355

推薦閱讀更多精彩內(nèi)容