微信小程序_(校園視) 開發用戶註冊登錄 傳送門 html
微信小程序_(校園視) 開發上傳視頻業務 傳送門 前端
微信小程序_(校園視) 開發視頻的展現頁-上 傳送門 java
微信小程序_(校園視) 開發視頻的展現頁-下 傳送門 git
小程序的頁面攔截github
當頁面點擊右下角的小圖標後,觸發showMain()事件,跳轉到mine.wxml,展現我的信息頁面,點擊作下表的小房子跳轉到視頻首頁web
<!-- 個人按鈕 --> <cover-image class='' src='../resource/images/mine.png' class="size-bottom" bindtap='showMine'></cover-image>
<!-- 首頁按鈕 --> <cover-image class='' src='../resource/images/index.png' class="size-bottom" bindtap='showIndex'></cover-image>
showIndex:function(){ wx.redirectTo({ url: '../index/index', }) }, showMine:function(){ var user = app.getGlobalUserInfo(); if(user ==null || user == undefined||user == ''){ wx.navigateTo({ url: '../userLogin/login', }) }else{ wx.navigateTo({ url: '../mine/mine', }) } }
在api層添加MiniInterceptor.class對攔截器進行配置與註冊redis
//攔截請求,在controller調用以前 @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { if(true) { System.out.println("請求攔截..."); return false; } //false:請求被攔截 //true:放行請求 return true; }
package com.imooc; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import com.imooc.controller.interceptor.MiniInterceptor; @Configuration public class WebMvcConfig extends WebMvcConfigurerAdapter { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/**") .addResourceLocations("classpath:/META-INF/resources/") .addResourceLocations("file:F:/imooc-video-gary/"); } @Bean public MiniInterceptor miniInterceptor() { return new MiniInterceptor(); } @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(miniInterceptor()).addPathPatterns("/user/**"); super.addInterceptors(registry); } }
package com.imooc.controller.interceptor; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; public class MiniInterceptor implements HandlerInterceptor { //攔截請求,在controller調用以前 @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { if(true) { System.out.println("請求攔截..."); return false; } //false:請求被攔截 //true:放行請求 return true; } //請求controller以後,渲染視圖以前 @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { // TODO Auto-generated method stub } //請求controller以後,視圖渲染以後 @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { // TODO Auto-generated method stub } }
完善攔截而且限制用戶只能在一臺手機上登錄spring
在加載我的頁面mine.js的header中添加userId和userToken兩個參數數據庫
header: { 'content-type': 'application/json', // 默認值 'userId':user.id, 'userToken':user.userToken },
在MiniInterceptor.java中接收到小程序端傳遞的Header消息後進行攔截器的配置apache
//攔截請求,在controller調用以前 @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)throws Exception { //獲取來自小程序的兩個參數 String userId = request.getHeader("userId"); String userToken = request.getHeader("userToken"); if(StringUtils.isNotBlank(userId)&&StringUtils.isNotBlank(userToken)) { String uniqueToken = redis.get(USER_REDIS_SESSION + ":" + userId); if(StringUtils.isEmpty(uniqueToken)&&StringUtils.isBlank(uniqueToken)) { returnErrorResponse(response,new IMoocJSONResult().errorTokenMsg("請登陸...")); return false; }else { if(!uniqueToken.equals(userToken)) { returnErrorResponse(response,new IMoocJSONResult().errorTokenMsg("帳號被擠出...")); return false; } } }else{ returnErrorResponse(response,new IMoocJSONResult().errorTokenMsg("請登陸...")); return false; } //false:請求被攔截 //true:放行請求 return true; }
要將後端控制檯的消息返回給小程序端,須要用到returnErrorResponse(HttpServletResponse response, IMoocJSONResult result) 將消息轉換成JSON數據格式,再傳遞給小程序端口
//轉換成JSON數據格式 public void returnErrorResponse(HttpServletResponse response, IMoocJSONResult result) throws IOException, UnsupportedEncodingException { OutputStream out=null; try{ response.setCharacterEncoding("utf-8"); response.setContentType("text/json"); out = response.getOutputStream(); //拋出信息 out.write(JsonUtils.objectToJson(result).getBytes("utf-8")); out.flush(); } finally{ if(out!=null){ out.close(); } } }
package com.imooc.controller.interceptor; import java.io.IOException; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import com.imooc.utils.IMoocJSONResult; import com.imooc.utils.JsonUtils; import com.imooc.utils.RedisOperator; public class MiniInterceptor implements HandlerInterceptor { @Autowired public RedisOperator redis; public static final String USER_REDIS_SESSION = "user-redis-session"; //攔截請求,在controller調用以前 @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)throws Exception { //獲取來自小程序的兩個參數 String userId = request.getHeader("userId"); String userToken = request.getHeader("userToken"); if(StringUtils.isNotBlank(userId)&&StringUtils.isNotBlank(userToken)) { String uniqueToken = redis.get(USER_REDIS_SESSION + ":" + userId); if(StringUtils.isEmpty(uniqueToken)&&StringUtils.isBlank(uniqueToken)) { returnErrorResponse(response,new IMoocJSONResult().errorTokenMsg("請登陸...")); return false; }else { if(!uniqueToken.equals(userToken)) { returnErrorResponse(response,new IMoocJSONResult().errorTokenMsg("帳號被擠出...")); return false; } } }else{ returnErrorResponse(response,new IMoocJSONResult().errorTokenMsg("請登陸...")); return false; } //false:請求被攔截 //true:放行請求 return true; } //轉換成JSON數據格式 public void returnErrorResponse(HttpServletResponse response, IMoocJSONResult result) throws IOException, UnsupportedEncodingException { OutputStream out=null; try{ response.setCharacterEncoding("utf-8"); response.setContentType("text/json"); out = response.getOutputStream(); //拋出信息 out.write(JsonUtils.objectToJson(result).getBytes("utf-8")); out.flush(); } finally{ if(out!=null){ out.close(); } } } //請求controller以後,渲染視圖以前 @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { // TODO Auto-generated method stub } //請求controller以後,視圖渲染以後 @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { // TODO Auto-generated method stub } }
先後端聯調測試攔截器
注:IMoocJSONResult errorTokenMsg(String msg)方法返回的狀態status是502
public static IMoocJSONResult errorTokenMsg(String msg) { return new IMoocJSONResult(502, msg, null); }
在微信小程序端進行狀態嗎的判斷
if (res.data.status == 502){ wx.showToast({ title: res.data.msg, duration:3000, icon:"none", success:function(){ wx.redirectTo({ url: '../userLogin/login', }) }
實現點贊與取消點贊功能先後端聯調
微信小程序點贊按鈕前端模塊
<!-- 喜歡收藏按鈕 --> <block wx:if="{{userLikeVideo}}"> <cover-image class="size-me" src='../resource/images/like.png' style='margin-top:30rpx;' bindtap='likeVideoOrNot'></cover-image> </block> <block wx:else> <cover-image class="size-me" src='../resource/images/unlike.png' style='margin-top:30rpx;' bindtap='likeVideoOrNot'></cover-image> </block>
VideosMapperCustom.java類中添加視頻喜歡的數量方法
//對視頻喜歡的數量進行累加 public void addVideoLikeCount(String videoId); //對視頻喜歡的數量進行累減 public void reduceVideoLikeCount(String videoId);
VideosMapperCustom.xml中添加對數據庫中進行查詢的SQL語句
<update id="addVideoLikeCount" parameterType="String"> update videos set like_counts = like_counts + 1 where id=#{videoId} </update> <update id="reduceVideoLikeCount" parameterType="String"> update videos set like_counts = like_counts - 1 where id=#{videoId} </update>
同理UsersMapper.java中添加用戶對視頻是否喜歡
//用戶受喜歡數累加 public void addReceiveLikeCount(String userId); //用戶受喜歡數累減 public void reduceReceiveLikeCount(String userId);
在UsersMapper.xml中添加對數據庫進行查詢的語句
<update id="addReceiveLikeCount" parameterType="String"> update users set receive_like_counts = receive_like_counts + 1 where id=#{userId} </update> <update id="reduceReceiveLikeCount" parameterType="String"> update users set receive_like_counts = receive_like_counts - 1 where id=#{userId} </update>
Service層中添加刪除用戶和視頻的喜歡和點贊關聯表
@Transactional(propagation = Propagation.REQUIRED) @Override public void userLikeVideo(String userId, String videoId, String videoCreateId) { //保存用戶和視頻的喜歡點贊關聯關係表 String likeId = sid.nextShort(); UsersLikeVideos ulv = new UsersLikeVideos(); ulv.setId(likeId); ulv.setUserId(userId); ulv.setVideoId(videoId); usersLikeVideosMapper.insert(ulv); //視頻喜歡數量累加 videosMapperCustom.addVideoLikeCount(videoId); //用戶受喜歡數量的累加 usersMapper.addReceiveLikeCount(userId); } @Transactional(propagation = Propagation.REQUIRED) @Override public void userUnLikeVideo(String userId, String videoId, String videoCreateId) { //1.刪除用戶和視頻的喜歡點贊關聯關係表 Example example = new Example(UsersLikeVideos.class); Criteria criteria = example.createCriteria(); criteria.andEqualTo("userId",userId); criteria.andEqualTo("videoId",videoId); usersLikeVideosMapper.deleteByExample(example); //視頻喜歡數量累減 videosMapperCustom.reduceVideoLikeCount(videoId); //用戶受喜歡數量的累減 usersMapper.reduceReceiveLikeCount(userId); }
package com.imooc.server.impl; import java.util.List; import org.n3r.idworker.Sid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import com.imooc.mapper.BgmMapper; import com.imooc.mapper.SearchRecordsMapper; import com.imooc.mapper.UsersLikeVideosMapper; import com.imooc.mapper.UsersMapper; import com.imooc.mapper.VideosMapper; import com.imooc.mapper.VideosMapperCustom; import com.imooc.pojo.Bgm; import com.imooc.pojo.SearchRecords; import com.imooc.pojo.Users; import com.imooc.pojo.UsersLikeVideos; import com.imooc.pojo.Videos; import com.imooc.pojo.vo.VideosVO; import com.imooc.service.BgmService; import com.imooc.service.UserService; import com.imooc.service.VideoService; import com.imooc.utils.PagedResult; import tk.mybatis.mapper.entity.Example; import tk.mybatis.mapper.entity.Example.Criteria; @Service public class VideoServiceImpl implements VideoService { @Autowired private VideosMapper videosMapper; @Autowired private UsersMapper usersMapper; @Autowired private VideosMapperCustom videosMapperCustom; @Autowired private SearchRecordsMapper searchRecordsMapper; @Autowired private UsersLikeVideosMapper usersLikeVideosMapper; @Autowired private Sid sid; @Transactional(propagation = Propagation.REQUIRED) @Override public String saveVideo(Videos video) { String id = sid.nextShort(); video.setId(id); videosMapper.insertSelective(video); return id; } @Transactional(propagation = Propagation.REQUIRED) @Override public void updateVideo(String videoId, String coverPath) { Videos video = new Videos(); video.setId(videoId); video.setCoverPath(coverPath); videosMapper.updateByPrimaryKeySelective(video); } @Transactional(propagation = Propagation.REQUIRED) @Override public PagedResult getAllVideos(Videos video,Integer isSaveRecord, Integer page, Integer pageSize) { //保存熱搜詞 String desc = video.getVideoDesc(); if(isSaveRecord!=null && isSaveRecord==1) { SearchRecords record = new SearchRecords(); String recordId = sid.nextShort(); record.setId(recordId); record.setContent(desc); searchRecordsMapper.insert(record); } PageHelper.startPage(page,pageSize); List<VideosVO> list= videosMapperCustom.queryAllVideos(desc); PageInfo<VideosVO> pageList = new PageInfo<>(list); PagedResult pagedResult = new PagedResult(); pagedResult.setPage(page); pagedResult.setTotal(pageList.getPages()); pagedResult.setRows(list); pagedResult.setRecords(pageList.getTotal()); return pagedResult; } @Transactional(propagation = Propagation.SUPPORTS) @Override public List<String> getHotwords() { return searchRecordsMapper.getHotwords(); } @Transactional(propagation = Propagation.REQUIRED) @Override public void userLikeVideo(String userId, String videoId, String videoCreateId) { //保存用戶和視頻的喜歡點贊關聯關係表 String likeId = sid.nextShort(); UsersLikeVideos ulv = new UsersLikeVideos(); ulv.setId(likeId); ulv.setUserId(userId); ulv.setVideoId(videoId); usersLikeVideosMapper.insert(ulv); //視頻喜歡數量累加 videosMapperCustom.addVideoLikeCount(videoId); //用戶受喜歡數量的累加 usersMapper.addReceiveLikeCount(userId); } @Transactional(propagation = Propagation.REQUIRED) @Override public void userUnLikeVideo(String userId, String videoId, String videoCreateId) { //1.刪除用戶和視頻的喜歡點贊關聯關係表 Example example = new Example(UsersLikeVideos.class); Criteria criteria = example.createCriteria(); criteria.andEqualTo("userId",userId); criteria.andEqualTo("videoId",videoId); usersLikeVideosMapper.deleteByExample(example); //視頻喜歡數量累減 videosMapperCustom.reduceVideoLikeCount(videoId); //用戶受喜歡數量的累減 usersMapper.reduceReceiveLikeCount(userId); } }
package com.imooc.controller; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.util.Date; import java.util.UUID; import org.apache.commons.lang3.StringUtils; import org.apache.tomcat.util.http.fileupload.IOUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import com.imooc.enums.VideoStatusEnum; import com.imooc.pojo.Bgm; import com.imooc.pojo.Users; import com.imooc.pojo.Videos; import com.imooc.service.BgmService; import com.imooc.service.VideoService; import com.imooc.utils.FetchVideoCover; import com.imooc.utils.IMoocJSONResult; import com.imooc.utils.MergeVideoMp3; import com.imooc.utils.PagedResult; import io.swagger.annotations.Api; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParams; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; @RestController @Api(value="視頻相關業務的接口",tags= {"視頻相關業務的controller"}) @RequestMapping("/video") public class VideoController extends BasicController{ @Autowired private BgmService bgmService; @Autowired private VideoService videoService; @ApiOperation(value="上傳視頻", notes="上傳視頻的接口") @ApiImplicitParams({ @ApiImplicitParam(name="userId",value="用戶id",required=true, dataType="String" ,paramType="form"), @ApiImplicitParam(name="bgmId",value="背景音樂id",required=false, dataType="String" ,paramType="form"), @ApiImplicitParam(name="videoSeconds",value="背景音樂播放長度",required=true, dataType="String" ,paramType="form"), @ApiImplicitParam(name="videoWidth",value="視頻的寬度",required=true, dataType="String" ,paramType="form"), @ApiImplicitParam(name="videoHeight",value="視頻的高度",required=true, dataType="String" ,paramType="form"), @ApiImplicitParam(name="desc",value="視頻的描述",required=false, dataType="String" ,paramType="form") }) @PostMapping(value="/upload",headers="content-type=multipart/form-data") public IMoocJSONResult uploadFace(String userId, String bgmId,double videoSeconds,int videoWidth,int videoHeight,String desc, @ApiParam(value="短視頻",required=true) MultipartFile file) throws Exception { if(StringUtils.isBlank(userId)) { return IMoocJSONResult.errorMsg("用戶id不能爲空..."); } //文件保存命名空間 //String fileSpace = "F:/imooc-video-gary"; //保存到數據庫中的相對路徑 String uploadPathDB = "/" + userId + "/video"; String coverPathDB = "/" + userId + "/video"; FileOutputStream fileOutputStream = null; InputStream inputStream = null; String finalVideoPath = ""; try { if( file != null ) { String fileName = file.getOriginalFilename(); //Gary.mp4 使用spilt進行分割 String fileNamePrefix = fileName.split("\\.")[0]; if(StringUtils.isNoneBlank(fileName)) { //文件上傳的最終保存路徑 finalVideoPath = FILE_SPACE + uploadPathDB + "/" + fileName; //設置數據庫保存的路徑 uploadPathDB += ("/" + fileName); coverPathDB = coverPathDB + "/" + fileNamePrefix + ".jpg"; File outFile = new File(finalVideoPath); if(outFile.getParentFile()!=null || !outFile.getParentFile().isDirectory()) { //建立父文件夾 outFile.getParentFile().mkdirs(); } fileOutputStream = new FileOutputStream(outFile); inputStream = file.getInputStream(); IOUtils.copy(inputStream, fileOutputStream); } }else { return IMoocJSONResult.errorMsg("上傳出錯..."); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); return IMoocJSONResult.errorMsg("上傳出錯..."); }finally { if(fileOutputStream != null) { fileOutputStream.flush(); fileOutputStream.close(); } } //判斷bgmId是否爲空, //若是不爲空,那就查詢bgm的信息,而且合併視頻生成新的視頻 if(StringUtils.isNotBlank(bgmId)) { Bgm bgm = bgmService.queryBgmById(bgmId); String mp3InputPath = FILE_SPACE + bgm.getPath(); //System.out.println("1:mp3InputPath + "+mp3InputPath); MergeVideoMp3 tool = new MergeVideoMp3(FFMPEG_EXE); String videoInputPath = finalVideoPath; String videdoOutputName = UUID.randomUUID().toString() + ".mp4"; uploadPathDB = "/" + userId + "/video" + "/" +videdoOutputName; finalVideoPath = FILE_SPACE + uploadPathDB; tool.convertor(videoInputPath, mp3InputPath, videoSeconds, finalVideoPath); } //對視頻封面進行截圖 FetchVideoCover videoInfo = new FetchVideoCover(FFMPEG_EXE); videoInfo.getCover(finalVideoPath,FILE_SPACE + coverPathDB); //保存視頻信息到數據庫 Videos video = new Videos(); video.setAudioId(bgmId); video.setUserId(userId); video.setVideoSeconds((float)videoSeconds); video.setVideoHeight(videoHeight); video.setVideoWidth(videoWidth); video.setVideoDesc(desc); video.setVideoPath(uploadPathDB); video.setCoverPath(coverPathDB); video.setStatus(VideoStatusEnum.SUCCESS.value); video.setCreateTime(new Date()); String videoId = videoService.saveVideo(video); return IMoocJSONResult.ok(videoId); } @ApiOperation(value="上傳封面", notes="上傳封面的接口") @ApiImplicitParams({ @ApiImplicitParam(name="userId",value="用戶id",required=true, dataType="String" ,paramType="form"), @ApiImplicitParam(name="videoId",value="視頻主鍵id",required=true, dataType="String" ,paramType="form") }) @PostMapping(value="/uploadCover",headers="content-type=multipart/form-data") public IMoocJSONResult uploadCover(String userId,String videoId, @ApiParam(value="視頻封面",required=true) MultipartFile file) throws Exception { if(StringUtils.isBlank(userId) ||StringUtils.isBlank(videoId) ) { return IMoocJSONResult.errorMsg("視頻主鍵id和用戶id不能爲空..."); } //文件保存命名空間 //String fileSpace = "F:/imooc-video-gary"; //保存到數據庫中的相對路徑 String uploadPathDB = "/" + userId + "/video"; FileOutputStream fileOutputStream = null; InputStream inputStream = null; String finalCoverPath = ""; try { if( file != null ) { String fileName = file.getOriginalFilename(); if(StringUtils.isNoneBlank(fileName)) { //文件上傳的最終保存路徑 finalCoverPath = FILE_SPACE + uploadPathDB + "/" + fileName; //設置數據庫保存的路徑 uploadPathDB += ("/" + fileName); File outFile = new File(finalCoverPath); if(outFile.getParentFile()!=null || !outFile.getParentFile().isDirectory()) { //建立父文件夾 outFile.getParentFile().mkdirs(); } fileOutputStream = new FileOutputStream(outFile); inputStream = file.getInputStream(); IOUtils.copy(inputStream, fileOutputStream); } }else { return IMoocJSONResult.errorMsg("上傳出錯..."); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); return IMoocJSONResult.errorMsg("上傳出錯..."); }finally { if(fileOutputStream != null) { fileOutputStream.flush(); fileOutputStream.close(); } } videoService.updateVideo(videoId, uploadPathDB); return IMoocJSONResult.ok(); } //分頁和搜索查詢視頻列表 //isSaveRecord:1 須要保存 0 不須要保存或爲空 @PostMapping(value="/showAll") public IMoocJSONResult showAll(@RequestBody Videos video,Integer isSaveRecord , Integer page) throws Exception { if(page == null) { page = 1; } PagedResult result = videoService.getAllVideos(video,isSaveRecord,page,PAGE_SIZE); return IMoocJSONResult.ok(result); } @PostMapping(value="/hot") public IMoocJSONResult hot() throws Exception { return IMoocJSONResult.ok(videoService.getHotwords()); } @PostMapping(value="/userLike") public IMoocJSONResult userLike(String userId,String videoId,String videoCreateId) throws Exception { videoService.userLikeVideo(userId, videoId, videoCreateId); return IMoocJSONResult.ok(); } @PostMapping(value="/userUnLike") public IMoocJSONResult userUnLike(String userId,String videoId,String videoCreateId) throws Exception { videoService.userUnLikeVideo(userId, videoId, videoCreateId); return IMoocJSONResult.ok(); } }
小程序點贊與取消點贊功能先後端聯調
在videoinfo.js中編寫用戶點贊與取消功能
likeVideoOrNot:function(){ var me = this; var videoInfo = me.data.videoInfo; var user = app.getGlobalUserInfo(); if (user == null || user == undefined || user == '') { wx.navigateTo({ url: '../userLogin/login', }) } else { var userLikeVideo = me.data.userLikeVideo; var url = '/video/userLike?userId=' + user.id + '&videoId=' + videoInfo.id +'&videoCreaterId='+videoInfo.userId; if(userLikeVideo){ var url = '/video/userUnLike?userId=' + user.id + '&videoId=' + videoInfo.id + '&videoCreaterId=' + videoInfo.userId; } var serverUrl = app.serverUrl; wx.showLoading({ title: '...', }) wx.request({ url: serverUrl+url, method:'POST', header: { 'content-type': 'application/json', // 默認值 'userId': user.id, 'userToken': user.userToken }, success:function(res){ wx.hideLoading(); me.setData({ userLikeVideo:!userLikeVideo }); } }) } }
<view style='width:100%;height:100%;'> <video id="myVideo" src="{{src}}" muted="{{true}}" autoplay="{{true}}" loop="{{true}}" enable-progress-gesture="{{false}}" style='width:100%;height:100%;' objectFit='{{cover}}' > <cover-view class='container'> <!-- 上傳視頻 --> <cover-image src='../resource/images/camera.png' style='width:50rpx;height:50rpx;' bindtap='upload'></cover-image> <!-- 搜索按鈕 --> <cover-image src='../resource/images/search.png' style='width:45rpx;height:45rpx;' bindtap='showSearch'></cover-image> </cover-view> <cover-view class='container-me'> <!-- 頭像 --> <cover-image class="face" src='{{publisher.faceImage}}' bindtap='showPublisher'></cover-image> <!-- 喜歡收藏按鈕 --> <block wx:if="{{userLikeVideo}}"> <cover-image class="size-me" src='../resource/images/like.png' style='margin-top:30rpx;' bindtap='likeVideoOrNot'></cover-image> </block> <block wx:else> <cover-image class="size-me" src='../resource/images/unlike.png' style='margin-top:30rpx;' bindtap='likeVideoOrNot'></cover-image> </block> <!-- 評論按鈕 --> <cover-image class="size-me" src='../resource/images/comments.png' style='margin-top:30rpx;' bindtap='leaveComment'></cover-image> <!-- 分享按鈕 --> <cover-image class="size-me" src='../resource/images/share.png' style='margin-top:30rpx;' bindtap='shareMe'></cover-image> </cover-view> <cover-view class='container-words'> <cover-view>@{{publisher.nickname}}</cover-view> <cover-view class='video-desc'>{{videoInfo.videoDesc}}</cover-view> </cover-view> <cover-view class='container-bottom'> <!-- 首頁按鈕 --> <cover-image class='' src='../resource/images/index.png' class="size-bottom" bindtap='showIndex'></cover-image> <!-- 個人關注 --> <cover-image class='' src='../resource/images/follow.png' class="size-bottom" bindtap='showFollow'></cover-image> <!-- 個人按鈕 --> <cover-image class='' src='../resource/images/mine.png' class="size-bottom" bindtap='showMine'></cover-image> </cover-view> </video> </view>
var videoUtil = require('../../utils/videoUtil.js') const app = getApp() Page({ data: { cover:"cover", videoId:"", src:"", videoInfo:{}, userLikeVideo:false }, videoCtx:{ }, onLoad:function(params){ var me = this; me.videoCtx = wx.createVideoContext("myVideo", me); //獲取上一個頁面傳入的參數 var videoInfo = JSON.parse(params.videoInfo); var height = videoInfo.videoHeight; var width = videoInfo.videoWidth; var cover = "cover"; if(width>=height){ cover=""; } me.setData({ videoInfo: videoInfo.id, src:app.serverUrl + videoInfo.videoPath, videoInfo: videoInfo, cover:cover }); }, onShow:function(){ var me = this; me.videoCtx.play(); }, onHide:function(){ var me = this; me.videoCtx.pause(); }, showSearch:function(){ wx.navigateTo({ url: '../searchVideo/searchVideo', }) }, upload:function(){ var me = this; var user = app.getGlobalUserInfo(); var videoInfo = JSON.stringify(me.data.videoInfo); var realUrl = '../videoinfo/videoinfo#videoInfo@'+videoInfo; if (user == null || user == undefined || user == '') { wx.navigateTo({ url: '../userLogin/login?redirectUrl=' +realUrl, }) } else { videoUtil.uploadVideo(); } }, showIndex:function(){ wx.redirectTo({ url: '../index/index', }) }, showMine:function(){ var user = app.getGlobalUserInfo(); if(user ==null || user == undefined||user == ''){ wx.navigateTo({ url: '../userLogin/login', }) }else{ wx.navigateTo({ url: '../mine/mine', }) } }, likeVideoOrNot:function(){ var me = this; var videoInfo = me.data.videoInfo; var user = app.getGlobalUserInfo(); if (user == null || user == undefined || user == '') { wx.navigateTo({ url: '../userLogin/login', }) } else { var userLikeVideo = me.data.userLikeVideo; var url = '/video/userLike?userId=' + user.id + '&videoId=' + videoInfo.id +'&videoCreaterId='+videoInfo.userId; if(userLikeVideo){ var url = '/video/userUnLike?userId=' + user.id + '&videoId=' + videoInfo.id + '&videoCreaterId=' + videoInfo.userId; } var serverUrl = app.serverUrl; wx.showLoading({ title: '...', }) wx.request({ url: serverUrl+url, method:'POST', header: { 'content-type': 'application/json', // 默認值 'userId': user.id, 'userToken': user.userToken }, success:function(res){ wx.hideLoading(); me.setData({ userLikeVideo:!userLikeVideo }); } }) } } })
當用戶對某一視頻點贊後,數據庫中後臺會獲得該用戶與點贊視頻對應的屬性值與視頻點贊數量
進入視頻展現頁面查詢後端接口信息
UserController.java中編寫後端queryPublisher請求信息
@PostMapping("/queryPublisher") public IMoocJSONResult queryPublisher(String loginUserId,String videoId, String publishUserId) throws Exception { if(StringUtils.isBlank(publishUserId)) { return IMoocJSONResult.errorMsg(""); } //查詢視頻發佈者的信息 Users userInfo = userService.queryUserInfo(publishUserId); UsersVO publisher = new UsersVO(); BeanUtils.copyProperties(userInfo, publisher); //查詢當前登錄者和視頻的點贊關係 boolean userLikeVideo = userService.isUserLikeVideo(loginUserId, videoId); PublisherVideo bean = new PublisherVideo(); bean.setPublisher(publisher); bean.setUserLikeVideo(userLikeVideo); return IMoocJSONResult.ok(bean); }
videoindo.js中編寫得到用戶信息請求方法
wx.request({ url: serverUrl + '/user/queryPublisher?loginUserId=' + loginUserId + "&videoId=" + videoInfo.id +"&publishUserId="+videoInfo.userId, method:'POST', success:function(res){ var publisher = res.data.data.publisher; var userLikeVideo = res.data.data.userLikeVideo; me.setData({ serverUrl: serverUrl, publisher: publisher, userLikeVideo: userLikeVideo, }); } }) },
進入index.js視頻頁面後,會展現該視頻上傳用戶者頭像及是否被當前用戶點贊
var videoUtil = require('../../utils/videoUtil.js') const app = getApp() Page({ data: { cover:"cover", videoId:"", src:"", videoInfo:{}, userLikeVideo:false }, videoCtx:{ }, onLoad:function(params){ var me = this; me.videoCtx = wx.createVideoContext("myVideo", me); //獲取上一個頁面傳入的參數 var videoInfo = JSON.parse(params.videoInfo); var height = videoInfo.videoHeight; var width = videoInfo.videoWidth; var cover = "cover"; if(width>=height){ cover=""; } me.setData({ videoInfo: videoInfo.id, src:app.serverUrl + videoInfo.videoPath, videoInfo: videoInfo, cover:cover }); var serverUrl = app.serverUrl; var user = app.getGlobalUserInfo(); var loginUserId = ""; if (user != null && user != undefined && user != '') { loginUserId = user.id; } wx.request({ url: serverUrl + '/user/queryPublisher?loginUserId=' + loginUserId + "&videoId=" + videoInfo.id +"&publishUserId="+videoInfo.userId, method:'POST', success:function(res){ var publisher = res.data.data.publisher; var userLikeVideo = res.data.data.userLikeVideo; me.setData({ serverUrl: serverUrl, publisher: publisher, userLikeVideo: userLikeVideo, }); } }) }, onShow:function(){ var me = this; me.videoCtx.play(); }, onHide:function(){ var me = this; me.videoCtx.pause(); }, showSearch:function(){ wx.navigateTo({ url: '../searchVideo/searchVideo', }) }, upload:function(){ var me = this; var user = app.getGlobalUserInfo(); var videoInfo = JSON.stringify(me.data.videoInfo); var realUrl = '../videoinfo/videoinfo#videoInfo@'+videoInfo; if (user == null || user == undefined || user == '') { wx.navigateTo({ url: '../userLogin/login?redirectUrl=' +realUrl, }) } else { videoUtil.uploadVideo(); } }, showIndex:function(){ wx.redirectTo({ url: '../index/index', }) }, showMine:function(){ var user = app.getGlobalUserInfo(); if(user ==null || user == undefined||user == ''){ wx.navigateTo({ url: '../userLogin/login', }) }else{ wx.navigateTo({ url: '../mine/mine', }) } }, likeVideoOrNot:function(){ var me = this; var videoInfo = me.data.videoInfo; var user = app.getGlobalUserInfo(); if (user == null || user == undefined || user == '') { wx.navigateTo({ url: '../userLogin/login', }) } else { var userLikeVideo = me.data.userLikeVideo; var url = '/video/userLike?userId=' + user.id + '&videoId=' + videoInfo.id +'&videoCreaterId='+videoInfo.userId; if(userLikeVideo){ var url = '/video/userUnLike?userId=' + user.id + '&videoId=' + videoInfo.id + '&videoCreaterId=' + videoInfo.userId; } var serverUrl = app.serverUrl; wx.showLoading({ title: '...', }) wx.request({ url: serverUrl+url, method:'POST', header: { 'content-type': 'application/json', // 默認值 'userId': user.id, 'userToken': user.userToken }, success:function(res){ wx.hideLoading(); me.setData({ userLikeVideo:!userLikeVideo }); } }) } } })
package com.imooc.controller; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.util.UUID; import org.apache.commons.lang3.StringUtils; import org.apache.tomcat.util.http.fileupload.IOUtils; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import com.imooc.pojo.Users; import com.imooc.pojo.vo.PublisherVideo; import com.imooc.pojo.vo.UsersVO; import com.imooc.service.UserService; import com.imooc.utils.IMoocJSONResult; import com.imooc.utils.MD5Utils; import io.swagger.annotations.Api; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiOperation; @RestController @Api(value="用戶相關業務的接口",tags= {"用戶相關業務的controller"}) @RequestMapping("/user") public class UserController extends BasicController { @Autowired private UserService userService; @ApiOperation(value="用戶上傳頭像", notes="用戶上傳頭像的接口") @ApiImplicitParam(name="userId",value="用戶id",required=true, dataType="String" ,paramType="query") @PostMapping("/uploadFace") public IMoocJSONResult uploadFace(String userId, @RequestParam("file") MultipartFile[] files) throws Exception { if(StringUtils.isBlank(userId)) { return IMoocJSONResult.errorMsg("用戶id不能爲空..."); } //文件保存命名空間 String fileSpace = "F:/imooc-video-gary"; //保存到數據庫中的相對路徑 String uploadPathDB = "/" + userId + "/face"; FileOutputStream fileOutputStream = null; InputStream inputStream = null; try { if( files != null && files.length>0 ) { String fileName = files[0].getOriginalFilename(); if(StringUtils.isNoneBlank(fileName)) { //文件上傳的最終保存路徑 String finalFacePath = fileSpace + uploadPathDB + "/" + fileName; //設置數據庫保存的路徑 uploadPathDB += ("/" + fileName); File outFile = new File(finalFacePath); if(outFile.getParentFile()!=null || !outFile.getParentFile().isDirectory()) { //建立父文件夾 outFile.getParentFile().mkdirs(); } fileOutputStream = new FileOutputStream(outFile); inputStream = files[0].getInputStream(); IOUtils.copy(inputStream, fileOutputStream); } }else { return IMoocJSONResult.errorMsg("上傳出錯..."); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); return IMoocJSONResult.errorMsg("上傳出錯..."); }finally { if(fileOutputStream != null) { fileOutputStream.flush(); fileOutputStream.close(); } } Users user = new Users(); user.setId(userId); user.setFaceImage(uploadPathDB); userService.updateUserInfo(user); return IMoocJSONResult.ok(uploadPathDB); } @ApiOperation(value="查詢用戶信息", notes="查詢用戶信息的接口") @ApiImplicitParam(name="userId",value="用戶id",required=true, dataType="String" ,paramType="query") @PostMapping("/query") public IMoocJSONResult query(String userId) throws Exception { if(StringUtils.isBlank(userId)) { return IMoocJSONResult.errorMsg("用戶id不能爲空..."); } Users userInfo = userService.queryUserInfo(userId); UsersVO userVO = new UsersVO(); BeanUtils.copyProperties(userInfo, userVO); return IMoocJSONResult.ok(userVO); } @PostMapping("/queryPublisher") public IMoocJSONResult queryPublisher(String loginUserId,String videoId, String publishUserId) throws Exception { if(StringUtils.isBlank(publishUserId)) { return IMoocJSONResult.errorMsg(""); } //查詢視頻發佈者的信息 Users userInfo = userService.queryUserInfo(publishUserId); UsersVO publisher = new UsersVO(); BeanUtils.copyProperties(userInfo, publisher); //查詢當前登錄者和視頻的點贊關係 boolean userLikeVideo = userService.isUserLikeVideo(loginUserId, videoId); PublisherVideo bean = new PublisherVideo(); bean.setPublisher(publisher); bean.setUserLikeVideo(userLikeVideo); return IMoocJSONResult.ok(bean); } }
查看視頻發佈者信息
編寫用戶點擊上傳視頻者頭像後跳轉到該用戶首頁信息方法showPublisher()
<!-- 頭像 --> <cover-image class="face" src='{{serverUrl}}{{publisher.faceImage}}' bindtap='showPublisher'></cover-image>
showPublisher:function(){ var me = this; var user = app.getGlobalUserInfo(); var videoInfo = me.data.videoInfo; var realUrl = '../mine/mine#publisherId@' + videoInfo.user; if (user == null || user == undefined || user == '') { wx.navigateTo({ url: '../userLogin/login?redirectUrl=' + realUrl, }) } else { wx.navigateTo({ url: '../mine/mine?publisherId='+videoInfo.user, }) } },
在mine.js中修改onLoad()函數並給一個參數值params做爲得到緩存中用戶信息
onLoad: function (params) { var me = this; // var user = app.userInfo; //fixme 修改原有的全局對象爲本地緩存 var user = app.getGlobalUserInfo(); var userId = user.id; var publisherId = params.publisherId; if (publisherId != null && publisherId != '' && publisherId!=undefined) { userId = publisherId; } wx.showLoading({ title: '請等待...', }); // 調用後端 var serverUrl = app.serverUrl; wx.request({ url: serverUrl + '/user/query?userId=' + userId, method: "POST", header: { 'content-type': 'application/json', // 默認值 'userId':user.id, 'userToken':user.userToken }, success: function (res) { console.log(res.data); wx.hideLoading(); if (res.data.status == 200) { var userInfo= res.data.data; var faceUrl = "../resource/images/noneface.png"; if (userInfo.faceImage != null && userInfo.faceImage != '' && userInfo.faceImage!=undefined){ faceUrl = serverUrl + userInfo.faceImage; } me.setData({ faceUrl: faceUrl, fansCounts: userInfo.fansCounts, followCounts: userInfo.followCounts, receiveLikeCounts: userInfo.receiveLikeCounts, nickname: userInfo.nickname }); } else if (res.data.status == 502){ wx.showToast({ title: res.data.msg, duration:3000, icon:"none", success:function(){ wx.redirectTo({ url: '../userLogin/login', }) } }) } } }) },
var videoUtil = require('../../utils/videoUtil.js') const app = getApp() Page({ data: { cover: "cover", videoId: "", src: "", videoInfo: {}, userLikeVideo: false }, videoCtx: { }, onLoad: function (params) { var me = this; me.videoCtx = wx.createVideoContext("myVideo", me); //獲取上一個頁面傳入的參數 var videoInfo = JSON.parse(params.videoInfo); var height = videoInfo.videoHeight; var width = videoInfo.videoWidth; var cover = "cover"; if (width >= height) { cover = ""; } me.setData({ videoInfo: videoInfo.id, src: app.serverUrl + videoInfo.videoPath, videoInfo: videoInfo, cover: cover }); var serverUrl = app.serverUrl; var user = app.getGlobalUserInfo(); var loginUserId = ""; if (user != null && user != undefined && user != '') { loginUserId = user.id; } wx.request({ url: serverUrl + '/user/queryPublisher?loginUserId=' + loginUserId + "&videoId=" + videoInfo.id + "&publishUserId=" + videoInfo.userId, method: 'POST', success: function (res) { var publisher = res.data.data.publisher; var userLikeVideo = res.data.data.userLikeVideo; me.setData({ serverUrl: serverUrl, publisher: publisher, userLikeVideo: userLikeVideo, }); } }) }, onShow: function () { var me = this; me.videoCtx.play(); }, onHide: function () { var me = this; me.videoCtx.pause(); }, showSearch: function () { wx.navigateTo({ url: '../searchVideo/searchVideo', }) }, showPublisher: function () { var me = this; var user = app.getGlobalUserInfo(); var videoInfo = me.data.videoInfo; var realUrl = '..mine/mine#videoInfo@' + videoInfo.userId; if (user == null || user == undefined || user == '') { wx.navigateTo({ url: '../userLogin/login?redirectUrl=' + realUrl, }) } else { wx.navigateTo({ url: '../mine/mine?publisherId='+videoInfo.userId, }) } }, upload: function () { var me = this; var user = app.getGlobalUserInfo(); var videoInfo = JSON.stringify(me.data.videoInfo); var realUrl = '../videoinfo/videoinfo#videoInfo@' + videoInfo; if (user == null || user == undefined || user == '') { wx.navigateTo({ url: '../userLogin/login?redirectUrl=' + realUrl, }) } else { videoUtil.uploadVideo(); } }, showIndex: function () { wx.redirectTo({ url: '../index/index', }) }, showMine: function () { var user = app.getGlobalUserInfo(); if (user == null || user == undefined || user == '') { wx.navigateTo({ url: '../userLogin/login', }) } else { wx.navigateTo({ url: '../mine/mine', }) } }, likeVideoOrNot: function () { var me = this; var videoInfo = me.data.videoInfo; var user = app.getGlobalUserInfo(); if (user == null || user == undefined || user == '') { wx.navigateTo({ url: '../userLogin/login', }) } else { var userLikeVideo = me.data.userLikeVideo; var url = '/video/userLike?userId=' + user.id + '&videoId=' + videoInfo.id + '&videoCreaterId=' + videoInfo.userId; if (userLikeVideo) { var url = '/video/userUnLike?userId=' + user.id + '&videoId=' + videoInfo.id + '&videoCreaterId=' + videoInfo.userId; } var serverUrl = app.serverUrl; wx.showLoading({ title: '...', }) wx.request({ url: serverUrl + url, method: 'POST', header: { 'content-type': 'application/json', // 默認值 'userId': user.id, 'userToken': user.userToken }, success: function (res) { wx.hideLoading(); me.setData({ userLikeVideo: !userLikeVideo }); } }) } } })
var videoUtil = require('../../utils/videoUtil.js') const app = getApp() Page({ data: { faceUrl: "../resource/images/noneface.png", }, onLoad: function (params) { var me = this; // var user = app.userInfo; //fixme 修改原有的全局對象爲本地緩存 var user = app.getGlobalUserInfo(); var userId = user.id; var publisherId = params.publisherId; if (publisherId != null && publisherId != '' && publisherId!=undefined) { userId = publisherId; } wx.showLoading({ title: '請等待...', }); // 調用後端 var serverUrl = app.serverUrl; wx.request({ url: serverUrl + '/user/query?userId=' + userId, method: "POST", header: { 'content-type': 'application/json', // 默認值 'userId':user.id, 'userToken':user.userToken }, success: function (res) { console.log(res.data); wx.hideLoading(); if (res.data.status == 200) { var userInfo= res.data.data; var faceUrl = "../resource/images/noneface.png"; if (userInfo.faceImage != null && userInfo.faceImage != '' && userInfo.faceImage!=undefined){ faceUrl = serverUrl + userInfo.faceImage; } me.setData({ faceUrl: faceUrl, fansCounts: userInfo.fansCounts, followCounts: userInfo.followCounts, receiveLikeCounts: userInfo.receiveLikeCounts, nickname: userInfo.nickname }); } else if (res.data.status == 502){ wx.showToast({ title: res.data.msg, duration:3000, icon:"none", success:function(){ wx.redirectTo({ url: '../userLogin/login', }) } }) } } }) }, logout:function(params){ //var user = app.userInfo; //fixme 修改原有的全局對象爲本地緩存 var user = app.getGlobalUserInfo(); var serverUrl = app.serverUrl; wx.showLoading({ title: '請等待...', }); // 調用後端 wx.request({ url: serverUrl + '/logout?userId='+user.id, method: "POST", header: { 'content-type': 'application/json' // 默認值 }, success: function (res) { console.log(res.data); wx.hideLoading(); if (res.data.status == 200) { // 註銷成功 wx.showToast({ title: '註銷成功', icon: 'success', duration: 2000 }); //清除全局用戶對象 //app.userInfo = null; //註銷之後,清空緩存 wx.removeStorageSync('userInfo') //頁面跳轉 wx.navigateTo({ url: '../userLogin/login', }) } } }) }, changeFace:function(){ var me = this; wx.chooseImage({ count: 1, sizeType: ['compressed'], sourceType: ['album'], success:function(res) { var tempFilePaths = res.tempFilePaths; console.log(tempFilePaths); wx.showLoading({ title: '上傳中...', }) var serverUrl = app.serverUrl; //fixme 修改原有的全局對象爲本地緩存 var userInfo = app.getGlobalUserInfo(); wx.uploadFile({ url: serverUrl+'/user/uploadFace?userId='+userInfo.id, filePath: tempFilePaths[0], name: 'file', header: { 'content-type': 'application/json' // 默認值 }, success: function (res) { var data = JSON.parse(res.data); console.log(data); wx.hideLoading(); if(data.status == 200){ wx.showToast({ title: '上傳成功', icon: "success" }); var imageUrl = data.data; me.setData({ faceUrl: serverUrl+imageUrl }); } else if (data.status == 500){ wx.showToast({ title: data.msg }); } } }) } }) }, uploadVideo:function(){ // videoUtil.uploadVideo(); var me =this; wx.chooseVideo({ sourceType: ['album'], success(res) { console.log(res); var duration = res.duration; var tmpheight = res.height; var tmpwidth = res.width; var tmpVideoUrl = res.tempFilePath; var tmpCoverUrl = res.thumbTempFilePath; if(duration>300){ wx.showToast({ title: '視頻長度不能超過5分鐘...', icon:"none", duration:2500 }) } else if(duration<3){ wx.showToast({ title: '視頻長度過短,請上傳超過3秒的視頻...', icon: "none", duration: 2500 }) }else{ //打開選擇bgm頁面 wx.navigateTo({ url: '../chooseBgm/chooseBgm?duration=' + duration + "&tmpheight=" + tmpheight + "&tmpwidth=" + tmpwidth + "&tmpVideoUrl=" + tmpVideoUrl + "&tmpCoverUrl=" + tmpCoverUrl , }) } } }) } })
關注於取消關注接口
查看數據庫中user表
在UserMapper.java中編寫增長粉絲數、增長關注數、減小粉絲數量、減小關注數量方法
//增長粉絲數 public void addFansCount(String userId); //增長關注數 public void addFollersCount(String userId); //減小粉絲數量 public void reduceFanCount(String userId); //減小關注數量 public void reduceFollersCount(String userId);
在UserMapper.xml中實現SQL語句的編寫
<!-- 粉絲 --> <update id="addFansCount" parameterType="String"> update users set fans_counts = fans_counts + 1 where id=#{userId} </update> <update id="reduceFanCount" parameterType="String"> update users set fans_counts = fans_counts - 1 where id=#{userId} </update> <!-- 關注度 --> <update id="addFollersCount" parameterType="String"> update users set follow_counts = follow_counts + 1 where id=#{userId} </update> <update id="reduceFollersCount" parameterType="String"> update users set follow_counts = follow_counts - 1 where id=#{userId} </update>
Service層實現增長用戶粉絲和減小用戶粉絲方法
@Transactional(propagation = Propagation.REQUIRED) @Override public void saveUserFanRelation(String userId, String fanId) { String relId = sid.nextShort(); UsersFans userFan = new UsersFans(); userFan.setId(relId); userFan.setUserId(userId); userFan.setFanId(fanId); usersFansMapper.insert(userFan); userMapper.addFansCount(userId); userMapper.addFollersCount(fanId); } @Transactional(propagation = Propagation.REQUIRED) @Override public void deleteUserFanRelation(String userId, String fanId) { Example example = new Example(UsersFans.class); Criteria criteria = example.createCriteria(); criteria.andEqualTo("userId",userId); criteria.andEqualTo("fanId",fanId); usersFansMapper.deleteByExample(example); userMapper.reduceFollersCount(userId); userMapper.reduceFollersCount(fanId); }
Controller層去實現增長粉絲數beyourfans方法和減小粉絲數dontbeyourfans方法
@PostMapping("/beyourfans") public IMoocJSONResult beyourfans(String userId,String fanId) throws Exception { if(StringUtils.isBlank(userId)) { return IMoocJSONResult.errorMsg(""); } userService.saveUserFanRelation(userId, fanId); return IMoocJSONResult.ok("關注成功"); } @PostMapping("/dontbeyourfans") public IMoocJSONResult dontbeyourfans(String userId,String fanId) throws Exception { if(StringUtils.isBlank(userId)) { return IMoocJSONResult.errorMsg(""); } userService.deleteUserFanRelation(userId, fanId); return IMoocJSONResult.ok("取消關注成功"); }
@PostMapping("/beyourfans") public IMoocJSONResult beyourfans(String userId,String fanId) throws Exception { if(StringUtils.isBlank(userId)) { return IMoocJSONResult.errorMsg(""); } userService.saveUserFanRelation(userId, fanId); return IMoocJSONResult.ok("關注成功"); } @PostMapping("/dontbeyourfans") public IMoocJSONResult dontbeyourfans(String userId,String fanId) throws Exception { if(StringUtils.isBlank(userId)) { return IMoocJSONResult.errorMsg(""); } userService.deleteUserFanRelation(userId, fanId); return IMoocJSONResult.ok("取消關注成功"); }
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" > <mapper namespace="com.imooc.mapper.UsersMapper" > <resultMap id="BaseResultMap" type="com.imooc.pojo.Users" > <!-- WARNING - @mbg.generated --> <id column="id" property="id" jdbcType="VARCHAR" /> <result column="username" property="username" jdbcType="VARCHAR" /> <result column="password" property="password" jdbcType="VARCHAR" /> <result column="face_image" property="faceImage" jdbcType="VARCHAR" /> <result column="nickname" property="nickname" jdbcType="VARCHAR" /> <result column="fans_counts" property="fansCounts" jdbcType="INTEGER" /> <result column="receive_like_counts" property="receiveLikeCounts" jdbcType="INTEGER" /> <result column="follow_counts" property="followCounts" jdbcType="INTEGER" /> </resultMap> <!-- 受喜歡程度 --> <update id="addReceiveLikeCount" parameterType="String"> update users set receive_like_counts = receive_like_counts + 1 where id=#{userId} </update> <update id="reduceReceiveLikeCount" parameterType="String"> update users set receive_like_counts = receive_like_counts - 1 where id=#{userId} </update> <!-- 粉絲 --> <update id="addFansCount" parameterType="String"> update users set fans_counts = fans_counts + 1 where id=#{userId} </update> <update id="reduceFanCount" parameterType="String"> update users set fans_counts = fans_counts - 1 where id=#{userId} </update> <!-- 關注度 --> <update id="addFollersCount" parameterType="String"> update users set follow_counts = follow_counts + 1 where id=#{userId} </update> <update id="reduceFollersCount" parameterType="String"> update users set follow_counts = follow_counts - 1 where id=#{userId} </update> </mapper>
package com.imooc.server.impl; import java.util.List; import org.apache.commons.lang3.StringUtils; import org.n3r.idworker.Sid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import com.imooc.mapper.UsersFansMapper; import com.imooc.mapper.UsersLikeVideosMapper; import com.imooc.mapper.UsersMapper; import com.imooc.pojo.Users; import com.imooc.pojo.UsersFans; import com.imooc.pojo.UsersLikeVideos; import com.imooc.service.UserService; import com.imooc.utils.IMoocJSONResult; import tk.mybatis.mapper.entity.Example; import tk.mybatis.mapper.entity.Example.Criteria; @Service public class UserServiceImpl implements UserService { @Autowired private UsersMapper userMapper; @Autowired private UsersFansMapper usersFansMapper; @Autowired private UsersLikeVideosMapper usersLikeVideosMapper; @Autowired private Sid sid; @Transactional(propagation = Propagation.SUPPORTS) @Override public boolean queryUsernameIsExist(String username) { Users user = new Users(); user.setUsername(username); Users result = userMapper.selectOne(user); return result==null?false:true; } @Transactional(propagation = Propagation.REQUIRED) @Override public void saveUser(Users user) { String userId = sid.nextShort(); user.setId(userId); userMapper.insert(user); } @Transactional(propagation = Propagation.SUPPORTS) @Override public Users queryUserForLogin(String username, String password) { Example userExample = new Example(Users.class); Criteria criteria = userExample.createCriteria(); criteria.andEqualTo("username", username); criteria.andEqualTo("password", password); Users result = userMapper.selectOneByExample(userExample); return result; } @Transactional(propagation = Propagation.REQUIRED) @Override public void updateUserInfo(Users user) { Example userExample = new Example(Users.class); Criteria criteria = userExample.createCriteria(); criteria.andEqualTo("id",user.getId()); userMapper.updateByExampleSelective(user, userExample); } @Transactional(propagation = Propagation.SUPPORTS) @Override public Users queryUserInfo(String userId) { Example userExample = new Example(Users.class); Criteria criteria = userExample.createCriteria(); criteria.andEqualTo("id",userId); Users user = userMapper.selectOneByExample(userExample); return user; } @Transactional(propagation = Propagation.SUPPORTS) @Override public Boolean isUserLikeVideo(String userId, String videoId) { if(StringUtils.isBlank(userId)||StringUtils.isBlank(videoId)) { return false; } Example example = new Example(UsersLikeVideos.class); Criteria criteria = example.createCriteria(); criteria.andEqualTo("userId", userId); criteria.andEqualTo("videoId", videoId); List<UsersLikeVideos> list = usersLikeVideosMapper.selectByExample(example); if(list!=null &&list.size()>0) { return true; } return null; } @Transactional(propagation = Propagation.REQUIRED) @Override public void saveUserFanRelation(String userId, String fanId) { String relId = sid.nextShort(); UsersFans userFan = new UsersFans(); userFan.setId(relId); userFan.setUserId(userId); userFan.setFanId(fanId); usersFansMapper.insert(userFan); userMapper.addFansCount(userId); userMapper.addFollersCount(fanId); } @Transactional(propagation = Propagation.REQUIRED) @Override public void deleteUserFanRelation(String userId, String fanId) { Example example = new Example(UsersFans.class); Criteria criteria = example.createCriteria(); criteria.andEqualTo("userId",userId); criteria.andEqualTo("fanId",fanId); usersFansMapper.deleteByExample(example); userMapper.reduceFollersCount(userId); userMapper.reduceFollersCount(fanId); } }
package com.imooc.controller; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.util.UUID; import org.apache.commons.lang3.StringUtils; import org.apache.tomcat.util.http.fileupload.IOUtils; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import com.imooc.pojo.Users; import com.imooc.pojo.vo.PublisherVideo; import com.imooc.pojo.vo.UsersVO; import com.imooc.service.UserService; import com.imooc.utils.IMoocJSONResult; import com.imooc.utils.MD5Utils; import io.swagger.annotations.Api; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiOperation; @RestController @Api(value="用戶相關業務的接口",tags= {"用戶相關業務的controller"}) @RequestMapping("/user") public class UserController extends BasicController { @Autowired private UserService userService; @ApiOperation(value="用戶上傳頭像", notes="用戶上傳頭像的接口") @ApiImplicitParam(name="userId",value="用戶id",required=true, dataType="String" ,paramType="query") @PostMapping("/uploadFace") public IMoocJSONResult uploadFace(String userId, @RequestParam("file") MultipartFile[] files) throws Exception { if(StringUtils.isBlank(userId)) { return IMoocJSONResult.errorMsg("用戶id不能爲空..."); } //文件保存命名空間 String fileSpace = "F:/imooc-video-gary"; //保存到數據庫中的相對路徑 String uploadPathDB = "/" + userId + "/face"; FileOutputStream fileOutputStream = null; InputStream inputStream = null; try { if( files != null && files.length>0 ) { String fileName = files[0].getOriginalFilename(); if(StringUtils.isNoneBlank(fileName)) { //文件上傳的最終保存路徑 String finalFacePath = fileSpace + uploadPathDB + "/" + fileName; //設置數據庫保存的路徑 uploadPathDB += ("/" + fileName); File outFile = new File(finalFacePath); if(outFile.getParentFile()!=null || !outFile.getParentFile().isDirectory()) { //建立父文件夾 outFile.getParentFile().mkdirs(); } fileOutputStream = new FileOutputStream(outFile); inputStream = files[0].getInputStream(); IOUtils.copy(inputStream, fileOutputStream); } }else { return IMoocJSONResult.errorMsg("上傳出錯..."); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); return IMoocJSONResult.errorMsg("上傳出錯..."); }finally { if(fileOutputStream != null) { fileOutputStream.flush(); fileOutputStream.close(); } } Users user = new Users(); user.setId(userId); user.setFaceImage(uploadPathDB); userService.updateUserInfo(user); return IMoocJSONResult.ok(uploadPathDB); } @ApiOperation(value="查詢用戶信息", notes="查詢用戶信息的接口") @ApiImplicitParam(name="userId",value="用戶id",required=true, dataType="String" ,paramType="query") @PostMapping("/query") public IMoocJSONResult query(String userId) throws Exception { if(StringUtils.isBlank(userId)) { return IMoocJSONResult.errorMsg("用戶id不能爲空..."); } Users userInfo = userService.queryUserInfo(userId); UsersVO userVO = new UsersVO(); BeanUtils.copyProperties(userInfo, userVO); return IMoocJSONResult.ok(userVO); } @PostMapping("/queryPublisher") public IMoocJSONResult queryPublisher(String loginUserId,String videoId, String publishUserId) throws Exception { if(StringUtils.isBlank(publishUserId)) { return IMoocJSONResult.errorMsg(""); } //查詢視頻發佈者的信息 Users userInfo = userService.queryUserInfo(publishUserId); UsersVO publisher = new UsersVO(); BeanUtils.copyProperties(userInfo, publisher); //查詢當前登錄者和視頻的點贊關係 boolean userLikeVideo = userService.isUserLikeVideo(loginUserId, videoId); PublisherVideo bean = new PublisherVideo(); bean.setPublisher(publisher); bean.setUserLikeVideo(userLikeVideo); return IMoocJSONResult.ok(bean); } @PostMapping("/beyourfans") public IMoocJSONResult beyourfans(String userId,String fanId) throws Exception { if(StringUtils.isBlank(userId)) { return IMoocJSONResult.errorMsg(""); } userService.saveUserFanRelation(userId, fanId); return IMoocJSONResult.ok("關注成功"); } @PostMapping("/dontbeyourfans") public IMoocJSONResult dontbeyourfans(String userId,String fanId) throws Exception { if(StringUtils.isBlank(userId)) { return IMoocJSONResult.errorMsg(""); } userService.deleteUserFanRelation(userId, fanId); return IMoocJSONResult.ok("取消關注成功"); } }
微信小程序關注用戶粉絲先後端聯調
在mine.js中添加粉絲followMe()函數方法
followMe:function(e){ var me = this; var user = app.getGlobalUserInfo(); var userId = user.id; var publisherId = me.data.publisherId; var followType = e.currentTarget.dataset.followtype; //1:關注 0:取消關注 var url =''; if (followType == '1') { url = '/user/beyourfans?userId=' + publisherId + '&fanId=' + userId; } else { url = '/user/dontbeyourfans?userId=' + publisherId + '&fanId=' + userId; } wx.showLoading(); wx.request({ url: app.serverUrl+url, method:'POST', header: { 'content-type': 'application/json', // 默認值 'headerUserId': user.id, 'headerUserToken': user.userToken }, success:function(){ wx.hideLoading(); if (followType == '1') { me.setData({ isFollow: true }) } else { me.setData({ isFollow: false }) } } }) },
var videoUtil = require('../../utils/videoUtil.js') const app = getApp() Page({ data: { faceUrl: "../resource/images/noneface.png", isMe:true, isFollow:false }, onLoad: function (params) { var me = this; // var user = app.userInfo; //fixme 修改原有的全局對象爲本地緩存 var user = app.getGlobalUserInfo(); var userId = user.id; var publisherId = params.publisherId; if (publisherId != null && publisherId != '' && publisherId!=undefined) { userId = publisherId; me.setData({ isMe:false, publisherId: publisherId }) } wx.showLoading({ title: '請等待...', }); var serverUrl = app.serverUrl; wx.request({ url: serverUrl + '/user/query?userId=' + userId, method: "POST", header: { 'content-type': 'application/json', // 默認值 'userId':user.id, 'userToken':user.userToken }, success: function (res) { console.log(res.data); wx.hideLoading(); if (res.data.status == 200) { var userInfo= res.data.data; var faceUrl = "../resource/images/noneface.png"; if (userInfo.faceImage != null && userInfo.faceImage != '' && userInfo.faceImage!=undefined){ faceUrl = serverUrl + userInfo.faceImage; } me.setData({ faceUrl: faceUrl, fansCounts: userInfo.fansCounts, followCounts: userInfo.followCounts, receiveLikeCounts: userInfo.receiveLikeCounts, nickname: userInfo.nickname }); } else if (res.data.status == 502){ wx.showToast({ title: res.data.msg, duration:3000, icon:"none", success:function(){ wx.redirectTo({ url: '../userLogin/login', }) } }) } } }) }, followMe:function(e){ var me = this; var user = app.getGlobalUserInfo(); var userId = user.id; var publisherId = me.data.publisherId; var followType = e.currentTarget.dataset.followtype; //1:關注 0:取消關注 var url =''; if (followType == '1') { url = '/user/beyourfans?userId=' + publisherId + '&fanId=' + userId; } else { url = '/user/dontbeyourfans?userId=' + publisherId + '&fanId=' + userId; } wx.showLoading(); wx.request({ url: app.serverUrl+url, method:'POST', header: { 'content-type': 'application/json', // 默認值 'headerUserId': user.id, 'headerUserToken': user.userToken }, success:function(){ wx.hideLoading(); if (followType == '1') { me.setData({ isFollow: true }) } else { me.setData({ isFollow: false }) } } }) }, logout:function(params){ //var user = app.userInfo; //fixme 修改原有的全局對象爲本地緩存 var user = app.getGlobalUserInfo(); var serverUrl = app.serverUrl; wx.showLoading({ title: '請等待...', }); // 調用後端 wx.request({ url: serverUrl + '/logout?userId='+user.id, method: "POST", header: { 'content-type': 'application/json' // 默認值 }, success: function (res) { console.log(res.data); wx.hideLoading(); if (res.data.status == 200) { // 註銷成功 wx.showToast({ title: '註銷成功', icon: 'success', duration: 2000 }); //清除全局用戶對象 //app.userInfo = null; //註銷之後,清空緩存 wx.removeStorageSync('userInfo') //頁面跳轉 wx.navigateTo({ url: '../userLogin/login', }) } } }) }, changeFace:function(){ var me = this; wx.chooseImage({ count: 1, sizeType: ['compressed'], sourceType: ['album'], success:function(res) { var tempFilePaths = res.tempFilePaths; console.log(tempFilePaths); wx.showLoading({ title: '上傳中...', }) var serverUrl = app.serverUrl; //fixme 修改原有的全局對象爲本地緩存 var userInfo = app.getGlobalUserInfo(); wx.uploadFile({ url: serverUrl+'/user/uploadFace?userId='+userInfo.id, filePath: tempFilePaths[0], name: 'file', header: { 'content-type': 'application/json', // 默認值 'headerUserId':userInfo.id, 'headerUserToken':userInfo.userToken }, success: function (res) { var data = JSON.parse(res.data); console.log(data); wx.hideLoading(); if(data.status == 200){ wx.showToast({ title: '上傳成功', icon: "success" }); var imageUrl = data.data; me.setData({ faceUrl: serverUrl+imageUrl }); } else if (data.status == 500){ wx.showToast({ title: data.msg }); } } }) } }) }, uploadVideo:function(){ // videoUtil.uploadVideo(); var me =this; wx.chooseVideo({ sourceType: ['album'], success(res) { console.log(res); var duration = res.duration; var tmpheight = res.height; var tmpwidth = res.width; var tmpVideoUrl = res.tempFilePath; var tmpCoverUrl = res.thumbTempFilePath; if(duration>300){ wx.showToast({ title: '視頻長度不能超過5分鐘...', icon:"none", duration:2500 }) } else if(duration<3){ wx.showToast({ title: '視頻長度過短,請上傳超過3秒的視頻...', icon: "none", duration: 2500 }) }else{ //打開選擇bgm頁面 wx.navigateTo({ url: '../chooseBgm/chooseBgm?duration=' + duration + "&tmpheight=" + tmpheight + "&tmpwidth=" + tmpwidth + "&tmpVideoUrl=" + tmpVideoUrl + "&tmpCoverUrl=" + tmpCoverUrl , }) } } }) } })
是否關注動態展現
在微信小程序端動態得到添加關注信息,當關注某一用戶後,下一次進該用戶首頁時,自動爲關注該用戶
@Override public boolean queryIfFollow(String userId, String fanId) { Example example = new Example(UsersFans.class); Criteria criteria = example.createCriteria(); criteria.andEqualTo("userId",userId); criteria.andEqualTo("fanId",fanId); List<UsersFans> list = usersFansMapper.selectByExample(example); if(list!=null && !list.isEmpty() &&list.size()>0) { return true; } return false; }
var videoUtil = require('../../utils/videoUtil.js') const app = getApp() Page({ data: { faceUrl: "../resource/images/noneface.png", isMe:true, isFollow:false }, onLoad: function (params) { var me = this; // var user = app.userInfo; //fixme 修改原有的全局對象爲本地緩存 var user = app.getGlobalUserInfo(); var userId = user.id; var publisherId = params.publisherId; if (publisherId != null && publisherId != '' && publisherId!=undefined) { userId = publisherId; me.setData({ isMe:false, publisherId: publisherId }) } wx.showLoading({ title: '請等待...', }); var serverUrl = app.serverUrl; wx.request({ url: serverUrl + '/user/query?userId=' + userId +"&fanId="+user.id, method: "POST", header: { 'content-type': 'application/json', // 默認值 'userId':user.id, 'userToken':user.userToken }, success: function (res) { console.log(res.data); wx.hideLoading(); if (res.data.status == 200) { var userInfo= res.data.data; var faceUrl = "../resource/images/noneface.png"; if (userInfo.faceImage != null && userInfo.faceImage != '' && userInfo.faceImage!=undefined){ faceUrl = serverUrl + userInfo.faceImage; } me.setData({ faceUrl: faceUrl, fansCounts: userInfo.fansCounts, followCounts: userInfo.followCounts, receiveLikeCounts: userInfo.receiveLikeCounts, nickname: userInfo.nickname, isFollow: userInfo.follow }); } else if (res.data.status == 502){ wx.showToast({ title: res.data.msg, duration:3000, icon:"none", success:function(){ wx.redirectTo({ url: '../userLogin/login', }) } }) } } }) }, followMe:function(e){ var me = this; var user = app.getGlobalUserInfo(); var userId = user.id; var publisherId = me.data.publisherId; var followType = e.currentTarget.dataset.followtype; //1:關注 0:取消關注 var url =''; if (followType == '1') { url = '/user/beyourfans?userId=' + publisherId + '&fanId=' + userId; } else { url = '/user/dontbeyourfans?userId=' + publisherId + '&fanId=' + userId; } wx.showLoading(); wx.request({ url: app.serverUrl+url, method:'POST', header: { 'content-type': 'application/json', // 默認值 'headerUserId': user.id, 'headerUserToken': user.userToken }, success:function(){ wx.hideLoading(); if (followType == '1') { me.setData({ isFollow: true }) } else { me.setData({ isFollow: false }) } } }) }, logout:function(params){ //var user = app.userInfo; //fixme 修改原有的全局對象爲本地緩存 var user = app.getGlobalUserInfo(); var serverUrl = app.serverUrl; wx.showLoading({ title: '請等待...', }); // 調用後端 wx.request({ url: serverUrl + '/logout?userId='+user.id, method: "POST", header: { 'content-type': 'application/json' // 默認值 }, success: function (res) { console.log(res.data); wx.hideLoading(); if (res.data.status == 200) { // 註銷成功 wx.showToast({ title: '註銷成功', icon: 'success', duration: 2000 }); //清除全局用戶對象 //app.userInfo = null; //註銷之後,清空緩存 wx.removeStorageSync('userInfo') //頁面跳轉 wx.navigateTo({ url: '../userLogin/login', }) } } }) }, changeFace:function(){ var me = this; wx.chooseImage({ count: 1, sizeType: ['compressed'], sourceType: ['album'], success:function(res) { var tempFilePaths = res.tempFilePaths; console.log(tempFilePaths); wx.showLoading({ title: '上傳中...', }) var serverUrl = app.serverUrl; //fixme 修改原有的全局對象爲本地緩存 var userInfo = app.getGlobalUserInfo(); wx.uploadFile({ url: serverUrl+'/user/uploadFace?userId='+userInfo.id, filePath: tempFilePaths[0], name: 'file', header: { 'content-type': 'application/json', // 默認值 'headerUserId':userInfo.id, 'headerUserToken':userInfo.userToken }, success: function (res) { var data = JSON.parse(res.data); console.log(data); wx.hideLoading(); if(data.status == 200){ wx.showToast({ title: '上傳成功', icon: "success" }); var imageUrl = data.data; me.setData({ faceUrl: serverUrl+imageUrl }); } else if (data.status == 500){ wx.showToast({ title: data.msg }); } } }) } }) }, uploadVideo:function(){ // videoUtil.uploadVideo(); var me =this; wx.chooseVideo({ sourceType: ['album'], success(res) { console.log(res); var duration = res.duration; var tmpheight = res.height; var tmpwidth = res.width; var tmpVideoUrl = res.tempFilePath; var tmpCoverUrl = res.thumbTempFilePath; if(duration>300){ wx.showToast({ title: '視頻長度不能超過5分鐘...', icon:"none", duration:2500 }) } else if(duration<3){ wx.showToast({ title: '視頻長度過短,請上傳超過3秒的視頻...', icon: "none", duration: 2500 }) }else{ //打開選擇bgm頁面 wx.navigateTo({ url: '../chooseBgm/chooseBgm?duration=' + duration + "&tmpheight=" + tmpheight + "&tmpwidth=" + tmpwidth + "&tmpVideoUrl=" + tmpVideoUrl + "&tmpCoverUrl=" + tmpCoverUrl , }) } } }) } })
發現點擊是否關注時粉絲數量沒有進行同步,在mine.js中進行粉絲數量動態顯示
success:function(){ wx.hideLoading(); if (followType == '1') { me.setData({ isFollow: true, fansCounts:++me.data.fansCounts }) } else { me.setData({ isFollow: false, fansCounts: --me.data.fansCounts }) }
var videoUtil = require('../../utils/videoUtil.js') const app = getApp() Page({ data: { faceUrl: "../resource/images/noneface.png", isMe:true, isFollow:false }, onLoad: function (params) { var me = this; // var user = app.userInfo; //fixme 修改原有的全局對象爲本地緩存 var user = app.getGlobalUserInfo(); var userId = user.id; var publisherId = params.publisherId; if (publisherId != null && publisherId != '' && publisherId!=undefined) { userId = publisherId; me.setData({ isMe:false, publisherId: publisherId }) } wx.showLoading({ title: '請等待...', }); var serverUrl = app.serverUrl; wx.request({ url: serverUrl + '/user/query?userId=' + userId +"&fanId="+user.id, method: "POST", header: { 'content-type': 'application/json', // 默認值 'userId':user.id, 'userToken':user.userToken }, success: function (res) { console.log(res.data); wx.hideLoading(); if (res.data.status == 200) { var userInfo= res.data.data; var faceUrl = "../resource/images/noneface.png"; if (userInfo.faceImage != null && userInfo.faceImage != '' && userInfo.faceImage!=undefined){ faceUrl = serverUrl + userInfo.faceImage; } me.setData({ faceUrl: faceUrl, fansCounts: userInfo.fansCounts, followCounts: userInfo.followCounts, receiveLikeCounts: userInfo.receiveLikeCounts, nickname: userInfo.nickname, isFollow: userInfo.follow }); } else if (res.data.status == 502){ wx.showToast({ title: res.data.msg, duration:3000, icon:"none", success:function(){ wx.redirectTo({ url: '../userLogin/login', }) } }) } } }) }, followMe:function(e){ var me = this; var user = app.getGlobalUserInfo(); var userId = user.id; var publisherId = me.data.publisherId; var followType = e.currentTarget.dataset.followtype; //1:關注 0:取消關注 var url =''; if (followType == '1') { url = '/user/beyourfans?userId=' + publisherId + '&fanId=' + userId; } else { url = '/user/dontbeyourfans?userId=' + publisherId + '&fanId=' + userId; } wx.showLoading(); wx.request({ url: app.serverUrl+url, method:'POST', header: { 'content-type': 'application/json', // 默認值 'headerUserId': user.id, 'headerUserToken': user.userToken }, success:function(){ wx.hideLoading(); if (followType == '1') { me.setData({ isFollow: true, fansCounts:++me.data.fansCounts }) } else { me.setData({ isFollow: false, fansCounts: --me.data.fansCounts }) } } }) }, logout:function(params){ //var user = app.userInfo; //fixme 修改原有的全局對象爲本地緩存 var user = app.getGlobalUserInfo(); var serverUrl = app.serverUrl; wx.showLoading({ title: '請等待...', }); // 調用後端 wx.request({ url: serverUrl + '/logout?userId='+user.id, method: "POST", header: { 'content-type': 'application/json' // 默認值 }, success: function (res) { console.log(res.data); wx.hideLoading(); if (res.data.status == 200) { // 註銷成功 wx.showToast({ title: '註銷成功', icon: 'success', duration: 2000 }); //清除全局用戶對象 //app.userInfo = null; //註銷之後,清空緩存 wx.removeStorageSync('userInfo') //頁面跳轉 wx.navigateTo({ url: '../userLogin/login', }) } } }) }, changeFace:function(){ var me = this; wx.chooseImage({ count: 1, sizeType: ['compressed'], sourceType: ['album'], success:function(res) { var tempFilePaths = res.tempFilePaths; console.log(tempFilePaths); wx.showLoading({ title: '上傳中...', }) var serverUrl = app.serverUrl; //fixme 修改原有的全局對象爲本地緩存 var userInfo = app.getGlobalUserInfo(); wx.uploadFile({ url: serverUrl+'/user/uploadFace?userId='+userInfo.id, filePath: tempFilePaths[0], name: 'file', header: { 'content-type': 'application/json', // 默認值 'headerUserId':userInfo.id, 'headerUserToken':userInfo.userToken }, success: function (res) { var data = JSON.parse(res.data); console.log(data); wx.hideLoading(); if(data.status == 200){ wx.showToast({ title: '上傳成功', icon: "success" }); var imageUrl = data.data; me.setData({ faceUrl: serverUrl+imageUrl }); } else if (data.status == 500){ wx.showToast({ title: data.msg }); } } }) } }) }, uploadVideo:function(){ // videoUtil.uploadVideo(); var me =this; wx.chooseVideo({ sourceType: ['album'], success(res) { console.log(res); var duration = res.duration; var tmpheight = res.height; var tmpwidth = res.width; var tmpVideoUrl = res.tempFilePath; var tmpCoverUrl = res.thumbTempFilePath; if(duration>300){ wx.showToast({ title: '視頻長度不能超過5分鐘...', icon:"none", duration:2500 }) } else if(duration<3){ wx.showToast({ title: '視頻長度過短,請上傳超過3秒的視頻...', icon: "none", duration: 2500 }) }else{ //打開選擇bgm頁面 wx.navigateTo({ url: '../chooseBgm/chooseBgm?duration=' + duration + "&tmpheight=" + tmpheight + "&tmpwidth=" + tmpwidth + "&tmpVideoUrl=" + tmpVideoUrl + "&tmpCoverUrl=" + tmpCoverUrl , }) } } }) } })