美文网首页
自动化打包脚本实现上传蒲公英通知钉钉群

自动化打包脚本实现上传蒲公英通知钉钉群

作者: 程序员阿兵 | 来源:发表于2021-01-27 17:20 被阅读0次
    • 创建task 任务
    //打包测试环境apk 上传蒲公英 发送邮件功能使用蒲公英自带的邮件功能
    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")
        }
    }
    
    

    上面执行任务packageDingTalk,然后构建apk任务

    • 上传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)
        //添加参数:_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}"
        //添加参数: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)
    
        //添加参数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)
    
    }
    

    根据蒲公英提供文档进行apk 上传

    • 发送通知到钉钉群
    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 = "[项目地址](${11111})"
        def _title = "蒲公英机器人"
        def _content = new StringBuffer()
        _content.append("\n\n###Android 测试包构建成功")
        _content.append("\n\n构建版本:1.0")
        _content.append("\n\n构建类型:dev")
        _content.append("\n\n下载地址:" + downloadUrl)
        _content.append("\n\n" + qrCodeUrl)
        _content.append("\n\n构建用户:桂雁彬")
        _content.append("\n\n构建时间:" + 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("*************** 钉钉消息已发送 ***************")
    }
    
    

    执行任务

    ./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)
        //添加参数:_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}"
        //添加参数: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)
    
        //添加参数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)
    
    }
    
    //打包测试环境apk 上传蒲公英 发送邮件功能使用蒲公英自带的邮件功能
    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"""// 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= "蒲公英机器人"
        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 = "[项目地址](${11111})"
    
        def _title = "蒲公英机器人"
        def _content = new StringBuffer()
        _content.append("\n\n###Android 测试包构建成功")
        _content.append("\n\n构建版本:1.0")
        _content.append("\n\n构建类型:dev")
        _content.append("\n\n下载地址:" + downloadUrl)
        _content.append("\n\n" + qrCodeUrl)
        _content.append("\n\n构建用户:桂雁彬")
        _content.append("\n\n构建时间:" + 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("*************** 钉钉消息已发送 ***************")
    }
    
    
    //获取当前时间
    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;
    }
    ```https://www.jianshu.com/p/82c4ed377385

    相关文章

      网友评论

          本文标题:自动化打包脚本实现上传蒲公英通知钉钉群

          本文链接:https://www.haomeiwen.com/subject/pspazktx.html