Browse Source

云信demo

wangqifan 3 years ago
parent
commit
76d2d3b76e

+ 36 - 0
src/main/java/com/izouma/nineth/domain/NeteaseUser.java

@@ -0,0 +1,36 @@
+package com.izouma.nineth.domain;
+
+import lombok.AllArgsConstructor;
+import lombok.Builder;
+import lombok.Data;
+import lombok.NoArgsConstructor;
+import org.hibernate.internal.util.StringHelper;
+
+import javax.persistence.Entity;
+import javax.persistence.Id;
+
+@Entity
+@Data
+@NoArgsConstructor
+@AllArgsConstructor
+@Builder
+public class NeteaseUser extends BaseEntityNoID {
+    @Id
+    private Long userId;
+
+    private String accId;
+
+    private String token;
+
+    private String name;
+
+    private String icon;
+
+    private String sign;
+
+    private String email;
+
+    private String mobile;
+
+    private String ex;
+}

+ 16 - 0
src/main/java/com/izouma/nineth/repo/NeteaseUserRepo.java

@@ -0,0 +1,16 @@
+package com.izouma.nineth.repo;
+
+import com.izouma.nineth.domain.NeteaseUser;
+import org.springframework.data.jpa.repository.JpaRepository;
+import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
+import org.springframework.data.jpa.repository.Modifying;
+import org.springframework.data.jpa.repository.Query;
+
+import javax.transaction.Transactional;
+
+public interface NeteaseUserRepo extends JpaRepository<NeteaseUser, Long>, JpaSpecificationExecutor<NeteaseUser> {
+    @Query("update NeteaseUser t set t.del = true where t.id = ?1")
+    @Modifying
+    @Transactional
+    void softDelete(Long id);
+}

+ 80 - 0
src/main/java/com/izouma/nineth/service/netease/NeteaseUserService.java

@@ -0,0 +1,80 @@
+package com.izouma.nineth.service.netease;
+
+import com.alibaba.fastjson.JSON;
+import com.alibaba.fastjson.JSONObject;
+import com.github.kevinsawicki.http.HttpRequest;
+import com.izouma.nineth.domain.NeteaseUser;
+import com.izouma.nineth.domain.User;
+import com.izouma.nineth.dto.PageQuery;
+import com.izouma.nineth.exception.BusinessException;
+import com.izouma.nineth.repo.NeteaseUserRepo;
+import com.izouma.nineth.repo.UserRepo;
+import com.izouma.nineth.utils.JpaUtils;
+import com.izouma.nineth.utils.netease.CheckSumBuilder;
+import lombok.AllArgsConstructor;
+import org.apache.commons.lang.RandomStringUtils;
+import org.springframework.data.domain.Page;
+import org.springframework.stereotype.Service;
+
+import javax.print.DocFlavor;
+import java.sql.Timestamp;
+import java.time.LocalDateTime;
+import java.time.ZoneOffset;
+import java.util.HashMap;
+import java.util.Map;
+
+@Service
+@AllArgsConstructor
+public class NeteaseUserService {
+
+    private NeteaseUserRepo neteaseUserRepo;
+    private UserRepo        userRepo;
+
+    public Page<NeteaseUser> all(PageQuery pageQuery) {
+        return neteaseUserRepo
+                .findAll(JpaUtils.toSpecification(pageQuery, NeteaseUser.class), JpaUtils.toPageRequest(pageQuery));
+    }
+
+    public String httpPost(String url, String contentType, Map<String, String> params) {
+        Map<String, String> headers = new HashMap<>();
+        String appKey = "872dd9d0a0f8eda25b579654745db459";
+        String nonce = RandomStringUtils.randomAlphabetic(32);
+        Timestamp timestamp = new Timestamp(LocalDateTime.now(ZoneOffset.UTC).toInstant(ZoneOffset.UTC).getEpochSecond());
+        String curTime = String.valueOf(timestamp.getTime());
+        String appSecret = "24e63777e4bb";
+        headers.put("AppKey", appKey);
+        headers.put("Nonce", nonce);
+        headers.put("CurTime", curTime);
+        headers.put("CheckSum", CheckSumBuilder.getCheckSum(appSecret, nonce, curTime));
+        return HttpRequest.post("https://api.netease.im/nimserver/" + url)
+                .contentType(contentType)
+                .headers(headers)
+                .form(params)
+                .body();
+    }
+
+    public NeteaseUser create(Long userId) {
+        User user = userRepo.findById(userId).orElseThrow(new BusinessException("暂无用户信息"));
+        String url = "user/create.action";
+        String contentType = "application/x-www-form-urlencoded;charset=utf-8";
+        Map<String, String> params = new HashMap<>();
+        params.put("accid", String.valueOf(user.getId()));
+        params.put("name", user.getNickname());
+        params.put("mobile", "+86-" + user.getPhone());
+        params.put("icon", user.getAvatar());
+        String result = httpPost(url, contentType, params);
+        JSONObject jsonObject = JSON.parseObject(result);
+        Integer code = jsonObject.getInteger("code");
+        if (code != 200) {
+            throw new BusinessException("注册出错,请核查后重新注册");
+        }
+        JSONObject info = jsonObject.getJSONObject("info");
+        String accId = info.getString("accid");
+        String name = info.getString("name");
+        String token = info.getString("token");
+        String icon = info.getString("icon");
+        NeteaseUser neteaseUser = NeteaseUser.builder().accId(accId).userId(userId).name(name).token(token).icon(icon)
+                .build();
+        return neteaseUserRepo.save(neteaseUser);
+    }
+}

+ 42 - 0
src/main/java/com/izouma/nineth/utils/netease/CheckSumBuilder.java

@@ -0,0 +1,42 @@
+package com.izouma.nineth.utils.netease;
+
+import java.security.MessageDigest;
+
+public class CheckSumBuilder {
+    // 计算并获取CheckSum
+    public static String getCheckSum(String appSecret, String nonce, String curTime) {
+        return encode("sha1", appSecret + nonce + curTime);
+    }
+
+    // 计算并获取md5值
+    public static String getMD5(String requestBody) {
+        return encode("md5", requestBody);
+    }
+
+    private static String encode(String algorithm, String value) {
+        if (value == null) {
+            return null;
+        }
+        try {
+            MessageDigest messageDigest
+                    = MessageDigest.getInstance(algorithm);
+            messageDigest.update(value.getBytes());
+            return getFormattedText(messageDigest.digest());
+        } catch (Exception e) {
+            throw new RuntimeException(e);
+        }
+    }
+
+    private static String getFormattedText(byte[] bytes) {
+        int len = bytes.length;
+        StringBuilder buf = new StringBuilder(len * 2);
+        for (int j = 0; j < len; j++) {
+            buf.append(HEX_DIGITS[(bytes[j] >> 4) & 0x0f]);
+            buf.append(HEX_DIGITS[bytes[j] & 0x0f]);
+        }
+        return buf.toString();
+    }
+
+    private static final char[] HEX_DIGITS = {'0', '1', '2', '3', '4', '5',
+            '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
+}

+ 65 - 0
src/main/java/com/izouma/nineth/web/NeteaseUserController.java

@@ -0,0 +1,65 @@
+package com.izouma.nineth.web;
+
+import com.izouma.nineth.domain.NeteaseUser;
+import com.izouma.nineth.service.netease.NeteaseUserService;
+import com.izouma.nineth.dto.PageQuery;
+import com.izouma.nineth.exception.BusinessException;
+import com.izouma.nineth.repo.NeteaseUserRepo;
+import com.izouma.nineth.utils.ObjUtils;
+import com.izouma.nineth.utils.excel.ExcelUtils;
+import lombok.AllArgsConstructor;
+import org.springframework.data.domain.Page;
+import org.springframework.web.bind.annotation.*;
+
+import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
+import java.util.List;
+
+@RestController
+@RequestMapping("/neteaseUser")
+@AllArgsConstructor
+public class NeteaseUserController extends BaseController {
+    private NeteaseUserService neteaseUserService;
+    private NeteaseUserRepo    neteaseUserRepo;
+
+    //@PreAuthorize("hasRole('ADMIN')")
+    @PostMapping("/save")
+    public NeteaseUser save(@RequestBody NeteaseUser record) {
+        if (record.getUserId() != null) {
+            NeteaseUser orig = neteaseUserRepo.findById(record.getUserId()).orElseThrow(new BusinessException("无记录"));
+            ObjUtils.merge(orig, record);
+            return neteaseUserRepo.save(orig);
+        }
+        return neteaseUserRepo.save(record);
+    }
+
+
+    //@PreAuthorize("hasRole('ADMIN')")
+    @PostMapping("/all")
+    public Page<NeteaseUser> all(@RequestBody PageQuery pageQuery) {
+        return neteaseUserService.all(pageQuery);
+    }
+
+    @GetMapping("/get/{id}")
+    public NeteaseUser get(@PathVariable Long id) {
+        return neteaseUserRepo.findById(id).orElseThrow(new BusinessException("无记录"));
+    }
+
+    @PostMapping("/del/{id}")
+    public void del(@PathVariable Long id) {
+        neteaseUserRepo.softDelete(id);
+    }
+
+    @GetMapping("/excel")
+    @ResponseBody
+    public void excel(HttpServletResponse response, PageQuery pageQuery) throws IOException {
+        List<NeteaseUser> data = all(pageQuery).getContent();
+        ExcelUtils.export(response, data);
+    }
+
+    @PostMapping("/create")
+    public NeteaseUser all(@RequestParam Long userId) {
+        return neteaseUserService.create(userId);
+    }
+}
+

+ 9 - 1
src/main/vue/src/router.js

@@ -1435,7 +1435,15 @@ const router = new Router({
                     meta: {
                         title: '易拍邀请',
                     },
-                }
+                },
+                {
+                    path: '/neteaseUserList',
+                    name: 'NeteaseUserList',
+                    component: () => import(/* webpackChunkName: "neteaseUserList" */ '@/views/NeteaseUserList.vue'),
+                    meta: {
+                       title: '云信用户表',
+                    },
+               }
                 /**INSERT_LOCATION**/
             ]
         },

+ 192 - 0
src/main/vue/src/views/NeteaseUserList.vue

@@ -0,0 +1,192 @@
+<template>
+    <div  class="list-view">
+        <page-title>
+            <el-button @click="addRow" type="primary" icon="el-icon-plus" :disabled="fetchingData || downloading" class="filter-item">
+                新增
+            </el-button>
+            <el-button @click="download" icon="el-icon-upload2" :loading="downloading" :disabled="fetchingData" class="filter-item">
+                导出
+            </el-button>
+        </page-title>
+        <div class="filters-container">
+            <el-input
+                    placeholder="搜索..."
+                    v-model="search"
+                    clearable
+                    class="filter-item search"
+                    @keyup.enter.native="getData"
+            >
+                <el-button @click="getData" slot="append" icon="el-icon-search"> </el-button>
+            </el-input>
+        </div>
+        <el-table :data="tableData" row-key="id" ref="table"
+                  header-row-class-name="table-header-row"
+                  header-cell-class-name="table-header-cell"
+                  row-class-name="table-row" cell-class-name="table-cell"
+                  :height="tableHeight" v-loading="fetchingData">
+            <el-table-column v-if="multipleMode" align="center" type="selection"
+                             width="50">
+            </el-table-column>
+            <el-table-column prop="id" label="ID" width="100">
+            </el-table-column>
+                                <el-table-column prop="userId" label="用户id"
+>
+                    </el-table-column>
+                    <el-table-column prop="accId" label="云信账号id"
+>
+                    </el-table-column>
+                    <el-table-column prop="token" label="token"
+>
+                    </el-table-column>
+                    <el-table-column prop="name" label="昵称"
+>
+                    </el-table-column>
+                    <el-table-column prop="icon" label="头像"
+>
+                            <template slot-scope="{row}">
+                                <el-image style="width: 30px; height: 30px"
+                                          :src="row.icon" fit="cover"
+                                          :preview-src-list="[row.icon]"></el-image>
+                            </template>
+                    </el-table-column>
+                    <el-table-column prop="sign" label="签名"
+>
+                    </el-table-column>
+                    <el-table-column prop="email" label="邮箱"
+>
+                    </el-table-column>
+                    <el-table-column prop="mobile" label="手机"
+>
+                    </el-table-column>
+                    <el-table-column prop="ex" label="扩展信息"
+>
+                    </el-table-column>
+            <el-table-column
+                    label="操作"
+                    align="center"
+                    fixed="right"
+                    width="150">
+                <template slot-scope="{row}">
+                    <el-button @click="editRow(row)" type="primary" size="mini" plain>编辑</el-button>
+                    <el-button @click="deleteRow(row)" type="danger" size="mini" plain>删除</el-button>
+                </template>
+            </el-table-column>
+        </el-table>
+        <div class="pagination-wrapper">
+            <!-- <div class="multiple-mode-wrapper">
+                <el-button v-if="!multipleMode" @click="toggleMultipleMode(true)">批量编辑</el-button>
+                <el-button-group v-else>
+                    <el-button @click="operation1">批量操作1</el-button>
+                    <el-button @click="operation2">批量操作2</el-button>
+                    <el-button @click="toggleMultipleMode(false)">取消</el-button>
+                </el-button-group>
+            </div> -->
+            <el-pagination background @size-change="onSizeChange"
+                           @current-change="onCurrentChange" :current-page="page"
+                           :page-sizes="[10, 20, 30, 40, 50]" :page-size="pageSize"
+                           layout="total, sizes, prev, pager, next, jumper"
+                           :total="totalElements">
+            </el-pagination>
+        </div>
+
+    </div>
+</template>
+<script>
+    import { mapState } from "vuex";
+    import pageableTable from "@/mixins/pageableTable";
+
+    export default {
+        name: 'NeteaseUserList',
+        mixins: [pageableTable],
+        data() {
+            return {
+                multipleMode: false,
+                search: "",
+                url: "/neteaseUser/all",
+                downloading: false,
+            }
+        },
+        computed: {
+            selection() {
+                return this.$refs.table.selection.map(i => i.id);
+            }
+        },
+        methods: {
+            beforeGetData() {
+                return { search: this.search, query: { del: false } };
+            },
+            toggleMultipleMode(multipleMode) {
+                this.multipleMode = multipleMode;
+                if (!multipleMode) {
+                    this.$refs.table.clearSelection();
+                }
+            },
+            addRow() {
+                this.$router.push({
+                    path: "/neteaseUserEdit",
+                    query: {
+                        ...this.$route.query
+                    }
+                });
+            },
+            editRow(row) {
+                this.$router.push({
+                    path: "/neteaseUserEdit",
+                    query: {
+                    id: row.id
+                    }
+                });
+            },
+            download() {
+                this.downloading = true;
+                this.$axios
+                    .get("/neteaseUser/excel", { 
+                        responseType: "blob",
+                        params: { size: 10000 }
+                    })
+                    .then(res => {
+                        console.log(res);
+                        this.downloading = false;
+                        const downloadUrl = window.URL.createObjectURL(new Blob([res.data]));
+                        const link = document.createElement("a");
+                        link.href = downloadUrl;
+                        link.setAttribute(
+                            "download",
+                            res.headers["content-disposition"].split("filename=")[1]
+                        );
+                        document.body.appendChild(link);
+                        link.click();
+                        link.remove();
+                    })
+                    .catch(e => {
+                        console.log(e);
+                        this.downloading = false;
+                        this.$message.error(e.error);
+                    });
+            },
+            operation1() {
+                this.$notify({
+                    title: '提示',
+                    message: this.selection
+                });
+            },
+            operation2() {
+                this.$message('操作2');
+            },
+            deleteRow(row) {
+                this.$alert('删除将无法恢复,确认要删除么?', '警告', {type: 'error'}).then(() => {
+                    return this.$http.post(`/neteaseUser/del/${row.id}`)
+                }).then(() => {
+                    this.$message.success('删除成功');
+                    this.getData();
+                }).catch(e => {
+                    if (e !== 'cancel') {
+                        this.$message.error(e.error);
+                    }
+                })
+            },
+        }
+    }
+</script>
+<style lang="less" scoped>
+</style>