public override void OnParameterInvaliding(HttpActionContext actionContext, ValidationFailedResult result) { var message = result.Data.FirstOrDefault()?.Message; actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.BadRequest, OperatedResult <string> .Fail(message)); }
/// <summary> /// 验证Token令牌是否合法 /// </summary> /// <param name="token">令牌</param> /// <param name="appid">应用ID</param> /// <returns>CheckResult</returns> protected virtual OperatedResult <string> CheckIdentityToken(string token, Guid appid) { #region 请求参数检查 var checkResult = CheckRequest(token, appid); if (!checkResult.State) { return(OperatedResult <string> .Fail(checkResult.Message)); } #endregion #region 请求通道检查 var getAppConfig = AppCfgService.Get(appid); if (!getAppConfig.State) { return(OperatedResult <string> .Fail(getAppConfig.Message)); } var appConfig = getAppConfig.Data; #endregion return(ApiAuthenticate.CheckIdentityToken(token, appConfig)); }
/// <summary> /// 通用图片上传类 /// </summary> /// <param name="postedFile">HttpPostedFile控件</param> /// <param name="savePath">保存路径</param> /// <returns>返回上传信息</returns> public OperatedResult <UploadImageInfo> FileSaveAs(HttpPostedFile postedFile, string savePath) { try { OperatedResult <UploadImageInfo> _uploadImageInfo = GetUploadImageInfo(postedFile, savePath); if (_uploadImageInfo.State) { string _fullPath = _uploadImageInfo.Data.FilePath, _fileEx = _uploadImageInfo.Data.FileEx, _fileName = _uploadImageInfo.Data.FileName; int _sourceWidth = _uploadImageInfo.Data.SourceWidth, _sourceHeight = _uploadImageInfo.Data.SourceHeight; HanlderImageSourceWidthOverMax(savePath, _sourceWidth, _sourceHeight, _fileEx, _fullPath); HanlderImageZip(_fullPath, _fileEx); HanlderThumbnailImage(_fullPath, savePath, _fileName, _fileEx, _sourceWidth, _sourceHeight, _uploadImageInfo.Data); HanlderSetPicWater(_fullPath, _uploadImageInfo.Data); HanlderSetTextWater(_fullPath, _uploadImageInfo.Data); return(OperatedResult <UploadImageInfo> .Success(_uploadImageInfo.Data)); } return(_uploadImageInfo); } catch (Exception ex) { return(OperatedResult <UploadImageInfo> .Fail(ex.Message)); } }
public OperatedResult <string> CheckIdentityToken(string token, AppConfig appConfig) { ValidateOperator.Begin() .NotNullOrEmpty(token, "Token") .NotNull(appConfig, "AppConfig"); try { var tokenText = ParseTokens(token, appConfig.SharedKey); if (string.IsNullOrEmpty(tokenText)) { return(OperatedResult <string> .Fail("用户令牌Token为空")); } dynamic root = JObject.Parse(tokenText); string userid = root.iss; var iat = root.iat; var validTokenExpired = new TimeSpan((int)(UnixEpochHelper.GetCurrentUnixTimestamp().TotalSeconds - iat)) .TotalDays > appConfig.TokenExpiredDay; return(validTokenExpired ? OperatedResult <string> .Fail($"用户ID{userid}令牌失效") : OperatedResult <string> .Success(userid)); } catch (FormatException) { return(OperatedResult <string> .Fail("用户令牌非法")); } catch (SignatureVerificationException) { return(OperatedResult <string> .Fail("用户令牌非法")); } }
/// <summary> /// 视频截图,默认BMP格式 /// </summary> /// <param name="saveImageFilePath">图片格式存储全路径;eg:D:\20170913162510.jpeg</param> /// <param name="imageType">图片格式</param> /// <returns>操作结果</returns> public OperatedResult Capture(string saveImageFilePath, CaptureImageType imageType = CaptureImageType.BMP) { if (!IsPreviewing) { return(OperatedResult.Fail("尚未处于视频预览状态,不能进行视频截图操作.")); } string _captureImageFile = string.IsNullOrEmpty(saveImageFilePath) != true ? saveImageFilePath : string.Format(@"{0}\{1}.{2}", CaptureFolders, DateTime.Now.ToString("yyyyMMddHHmmss"), imageType.ToString().ToLower()); bool _result = false; switch (imageType) { case CaptureImageType.BMP: _result = CHCNetSDK.NET_DVR_CapturePicture(previewId, _captureImageFile); break; case CaptureImageType.JPEG: CHCNetSDK.NET_DVR_JPEGPARA _jpegParamter = new CHCNetSDK.NET_DVR_JPEGPARA(); _jpegParamter.wPicQuality = 0; //图像质量 Image quality _jpegParamter.wPicSize = 0xff; //抓图分辨率 Picture size: 2- 4CIF,0xff- Auto(使用当前码流分辨率),抓图分辨率需要设备支持,更多取值请参考SDK文档 _result = CHCNetSDK.NET_DVR_CaptureJPEGPicture(UserId, CurPreviewChannelNo, ref _jpegParamter, _captureImageFile); break; } return(_result == true?OperatedResult.Success(_captureImageFile) : OperatedResult.Fail(LastErrorMessage)); }
/// <summary> /// 创建合法用户的Token /// </summary> /// <param name="userId">用户Id</param> /// <param name="passWord">用户密码</param> /// <param name="signature">加密签名字符串</param> /// <param name="timestamp">时间戳</param> /// <param name="nonce">随机数</param> /// <param name="appid">应用接入ID</param> /// <returns>OperatedResult</returns> protected virtual OperatedResult <IdentityToken> CreateIdentityToken(string userId, string passWord, string signature, string timestamp, string nonce, Guid appid) { #region 参数检查 var checkResult = CheckRequest(userId, passWord, signature, timestamp, nonce, appid); if (!checkResult.State) { return(OperatedResult <IdentityToken> .Fail(checkResult.Message)); } #endregion #region 用户鉴权 var getIdentityUser = GetIdentityUser(userId, passWord); if (!getIdentityUser.State) { return(OperatedResult <IdentityToken> .Fail(getIdentityUser.Message)); } #endregion #region 请求通道检查 var getAppConfig = AppCfgService.Get(appid); if (!getAppConfig.State) { return(OperatedResult <IdentityToken> .Fail(getAppConfig.Message)); } var appConfig = getAppConfig.Data; #endregion #region 检查请求签名检查 var checkSignatureResult = ApiAuthorize.CheckRequestSignature(signature, timestamp, nonce, appConfig); if (!checkSignatureResult.State) { return(OperatedResult <IdentityToken> .Fail(checkSignatureResult.Message)); } #endregion #region 生成基于Jwt Token var getTokenResult = ApiAuthorize.CreateIdentityToken(getIdentityUser.Data, getAppConfig.Data); if (!getTokenResult.State) { return(OperatedResult <IdentityToken> .Fail(getTokenResult.Message)); } return(OperatedResult <IdentityToken> .Success(getTokenResult.Data)); #endregion }
/// <summary> /// 用户登录 /// </summary> /// <returns>操作结果</returns> public OperatedResult Login() { if (LoginStatus) { return(OperatedResult.Fail("已经处于登陆状态,不能进行登陆操作.")); } CHCNetSDK.NET_DVR_DEVICEINFO_V30 _deviceInfo = new CHCNetSDK.NET_DVR_DEVICEINFO_V30(); UserId = CHCNetSDK.NET_DVR_Login_V30(VideoIPEndPoint.Address.ToString(), VideoIPEndPoint.Port, UserName, PassWord, ref _deviceInfo); return(LoginStatus == true?OperatedResult.Success() : OperatedResult.Fail(LastErrorMessage)); }
/// <summary> /// 开始录像 /// </summary> /// <param name="saveVideoFilePath">视频格式存储全路径;eg:D:\20170913162510.mp4</param> /// <returns>操作结果</returns> public OperatedResult StartRecord(string saveVideoFilePath) { if (!IsPreviewing) { return(OperatedResult.Fail("尚未处于视频预览状态,不能进行开始录像操作.")); } string _videoRecordFile = string.IsNullOrEmpty(saveVideoFilePath) != true ? saveVideoFilePath : string.Format(@"{0}\{1}.mp4", VideoFolders, DateTime.Now.ToString("yyyyMMddHHmmss")); CHCNetSDK.NET_DVR_MakeKeyFrame(UserId, CurPreviewChannelNo); IsRecording = CHCNetSDK.NET_DVR_SaveRealData(PreviewId, _videoRecordFile); return(IsRecording == true?OperatedResult.Success() : OperatedResult.Fail(LastErrorMessage)); }
/// <summary> /// 停止录像 /// </summary> /// <returns>操作结果</returns> public OperatedResult StopRecord() { if (!IsRecording) { return(OperatedResult.Fail("尚未处于视频录像状态,不能进行停止录像操作.")); } bool _result = CHCNetSDK.NET_DVR_StopSaveRealData(PreviewId); if (_result) { IsRecording = false; } return(_result == true?OperatedResult.Success() : OperatedResult.Fail(LastErrorMessage)); }
/// <summary> /// 注册用户获取访问令牌接口 /// </summary> /// <param name="userId">用户Id</param> /// <param name="passWord">用户密码</param> /// <param name="signature">加密签名字符串</param> /// <param name="timestamp">时间戳</param> /// <param name="nonce">随机数</param> /// <param name="appid">应用接入ID</param> /// <returns>OperatedResult</returns> public OperatedResult <TokenInfo> GetAccessToken(string userId, string passWord, string signature, string timestamp, string nonce, Guid appid) { CheckResult _checkedParamter = CheckedCreateAccessTokenParamter(userId, passWord, signature, timestamp, nonce, appid); if (!_checkedParamter.State) { return(OperatedResult <TokenInfo> .Fail(_checkedParamter.Message)); } #region 检查用户合法性 CheckResult <UserInfo> _checkedUser = CheckedUser(userId, passWord); if (!_checkedUser.State) { return(OperatedResult <TokenInfo> .Fail(_checkedUser.Message)); } #endregion 检查用户合法性 #region 检查api请求通道合法性 CheckResult <AppInfo> _checkedAppChannel = CheckedAppInfo(appid); if (!_checkedAppChannel.State) { return(OperatedResult <TokenInfo> .Fail(_checkedAppChannel.Message)); } AppInfo _appInfo = _checkedAppChannel.Data; #endregion 检查api请求通道合法性 #region 检查请求签名合法性 CheckResult _checkedSignature = SignatureHelper.Validate(signature, timestamp, nonce, _appInfo.AppSecret, _appInfo.SignatureExpiredMinutes); if (!_checkedSignature.State) { return(OperatedResult <TokenInfo> .Fail(_checkedSignature.Message)); } #endregion 检查请求签名合法性 UserInfo _userInfo = _checkedUser.Data; TokenInfo _tokenData = BuilderTokenInfo(_userInfo, _appInfo); return(OperatedResult <TokenInfo> .Success(_tokenData)); }
/// <summary> /// 用户登出 /// </summary> /// <returns>操作结果</returns> public OperatedResult Logout() { if (!LoginStatus) { return(OperatedResult.Fail("尚未处于登陆状态,不能进行登出操作.")); } if (CHCNetSDK.NET_DVR_Logout(UserId)) { UserId = -1; return(OperatedResult.Success()); } else { return(OperatedResult.Fail(LastErrorMessage)); } }
private OperatedResult <UploadImageInfo> GetUploadImageInfo(HttpPostedFile postedFile, string savePath) { CheckResult _checkedPostFileResult = CheckedPostFile(postedFile); if (!_checkedPostFileResult.State) { return(OperatedResult <UploadImageInfo> .Fail(_checkedPostFileResult.Message)); } int _randomNumber = RandomHelper.NextNumber(1000, 9999); string _fileName = DateTime.Now.FormatDate(12) + _randomNumber, _fileEx = Path.GetExtension(postedFile.FileName); double _fileSize = postedFile.ContentLength / 1024.0 / 1024.0; CheckResult _checkedUploadImageResult = CheckedUploadImageParamter(_fileEx, _fileSize); if (!_checkedUploadImageResult.State) { return(OperatedResult <UploadImageInfo> .Fail(_checkedUploadImageResult.Message)); } UploadImageInfo _uploadImageInfo = new UploadImageInfo(); _uploadImageInfo.FileName = _fileName + _fileEx; _uploadImageInfo.FilePath = savePath.Trim('\\') + "\\" + _uploadImageInfo.FileName; _uploadImageInfo.WebPath = "/" + _uploadImageInfo.FilePath.Replace(HttpContext.Current.Server.MapPath("~/"), "").Replace("\\", "/"); _uploadImageInfo.Size = _fileSize; _uploadImageInfo.FileEx = _fileEx; _uploadImageInfo.IsSetPicWater = !string.IsNullOrEmpty(SetPicWater); _uploadImageInfo.IsSetWordWater = !string.IsNullOrEmpty(SetWordWater); BitmapInfo _iamgeInfo = ImageHelper.GetBitmapInfo(postedFile.FileName); _uploadImageInfo.SourceWidth = _iamgeInfo.Width; _uploadImageInfo.SourceHeight = _iamgeInfo.Height; _uploadImageInfo.IsCreateThumbnail = SetSmallImgWidth.Length != 0; _uploadImageInfo.ThumbnailHeight = SetSmallImgHeight; _uploadImageInfo.ThumbnailWidth = SetSmallImgWidth; if (_uploadImageInfo.IsCreateThumbnail && SetSmallImgHeight.Length != SetSmallImgHeight.Length) { return(OperatedResult <UploadImageInfo> .Fail(GetCodeMessage(6))); } FileHelper.CreateDirectory(savePath); postedFile.SaveAs(_uploadImageInfo.FilePath); return(OperatedResult <UploadImageInfo> .Success(_uploadImageInfo)); }
/// <summary> /// 停止视频预览 /// </summary> /// <returns>操作结果</returns> public OperatedResult StopPreview() { if (!IsPreviewing) { return(OperatedResult.Fail("尚未处于视频预览状态,不能进行停止预览操作.")); } if (CHCNetSDK.NET_DVR_StopRealPlay(PreviewId)) { PreviewId = -1; CurPreviewChannelNo = 0; return(OperatedResult.Success()); } else { return(OperatedResult.Fail(LastErrorMessage)); } }
/// <summary> /// 验证Token令牌是否合法 /// </summary> /// <param name="token">令牌</param> /// <param name="appid">应用ID</param> /// <returns>CheckResult</returns> public OperatedResult <string> ValidateToken(string token, Guid appid) { CheckResult _checkedParamter = CheckedValidateTokenParamter(token, appid); if (!_checkedParamter.State) { return(OperatedResult <string> .Fail(_checkedParamter.Message)); } CheckResult <AppInfo> _checkedAppChannel = CheckedAppInfo(appid); if (!_checkedAppChannel.State) { return(OperatedResult <string> .Fail(_checkedAppChannel.Message)); } try { AppInfo _appInfo = _checkedAppChannel.Data; string _tokenString = JwtHelper.ParseTokens(token, _appInfo.SharedKey); if (string.IsNullOrEmpty(_tokenString)) { return(OperatedResult <string> .Fail("用户令牌Token为空")); } dynamic _root = JObject.Parse(_tokenString); string _userid = _root.iss; double _jwtcreated = (double)_root.iat; bool _validTokenExpired = (new TimeSpan((int)(UnixEpochHelper.GetCurrentUnixTimestamp().TotalSeconds - _jwtcreated)) .TotalDays) > _appInfo.TokenExpiredDay; return(_validTokenExpired == true ? OperatedResult <string> .Fail($"用户ID{_userid}令牌失效") : OperatedResult <string> .Success(_userid)); } catch (FormatException) { return(OperatedResult <string> .Fail("用户令牌非法")); } catch (SignatureVerificationException) { return(OperatedResult <string> .Fail("用户令牌非法")); } }
/// <summary> /// 保存表单文件,根据HttpPostedFile /// </summary> /// <param name="postFile">HttpPostedFile</param> /// <returns>上传返回信息</returns> private OperatedResult <UploadFileInfo> SaveUploadFile(HttpPostedFile postFile) { try { CheckResult <string> _checkedFileParamter = CheckedFileParamter(postFile); if (!_checkedFileParamter.State) { return(OperatedResult <UploadFileInfo> .Fail(_checkedFileParamter.Message)); } string _fileName = _checkedFileParamter.Data; string _webDir = string.Empty; // 获取存储目录 string _directory = this.GetDirectory(ref _webDir), _filePath = _directory + _fileName; if (File.Exists(_filePath)) { if (uploadFileSetting.IsRenameSameFile) { _filePath = _directory + DateTime.Now.FormatDate(12) + "-" + _fileName; } else { File.Delete(_filePath); } } // 保存文件 postFile.SaveAs(_filePath); UploadFileInfo _uploadFileInfo = new UploadFileInfo(); _uploadFileInfo.FilePath = _filePath; _uploadFileInfo.FilePath = _webDir + _fileName; _uploadFileInfo.FileName = _fileName; _uploadFileInfo.WebFilePath = _webDir + _fileName; return(OperatedResult <UploadFileInfo> .Success(_uploadFileInfo)); } catch (Exception ex) { return(OperatedResult <UploadFileInfo> .Fail(ex.Message)); } }
/// <summary> /// 视频预览 /// </summary> /// <returns>操作结果</returns> public OperatedResult Preview(ushort channelNumber, IntPtr previewUIHandle) { if (!LoginStatus) { return(OperatedResult.Fail("请先登陆后,再进行视频预览操作.")); } if (IsPreviewing) { return(OperatedResult.Fail("已经处于视频预览状态,不能进行视频预览操作.")); } CHCNetSDK.NET_DVR_PREVIEWINFO _previewParamter = new CHCNetSDK.NET_DVR_PREVIEWINFO(); _previewParamter.hPlayWnd = previewUIHandle; //预览窗口 _previewParamter.lChannel = channelNumber; //预te览的设备通道 _previewParamter.dwStreamType = 0; //码流类型:0-主码流,1-子码流,2-码流3,3-码流4,以此类推 _previewParamter.dwLinkMode = 0; //连接方式:0- TCP方式,1- UDP方式,2- 多播方式,3- RTP方式,4-RTP/RTSP,5-RSTP/HTTP _previewParamter.bBlocked = true; //0- 非阻塞取流,1- 阻塞取流 _previewParamter.dwDisplayBufNum = 15; //播放库播放缓冲区最大缓冲帧数 IntPtr _pUser = new IntPtr(); //用户数据 PreviewId = CHCNetSDK.NET_DVR_RealPlay_V40(UserId, ref _previewParamter, null /*RealData*/, _pUser); CurPreviewChannelNo = channelNumber; return(IsPreviewing == true?OperatedResult.Success() : OperatedResult.Fail(LastErrorMessage)); }
public override void OnParameterIsNulling(HttpActionContext actionContext) { actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.BadRequest, OperatedResult <string> .Fail("请求参数非法。")); }
/// <summary> /// 生成缩略图 /// </summary> /// <param name="originalImagePath">源图路径(物理路径)</param> /// <param name="thumbnailPath">缩略图路径(物理路径)</param> /// <param name="specifiedwidth">缩略图宽度</param> /// <param name="specifiedheight">缩略图高度</param> /// <param name="mode">生成缩略图的方式</param> /// <param name="isaddwatermark">是否添加水印</param> /// <param name="quality">图片品质</param> /// <param name="imagePosition">水印位置</param> /// <param name="waterImagePath">水印图片路径(物理路径)</param> public static OperatedResult <string> BuilderThumbnails(string originalImagePath, string thumbnailPath, int specifiedwidth, int specifiedheight, ThumbnailImageCutMode mode, bool isaddwatermark, WatermarkImagesPosition imagePosition, string waterImagePath, int quality) { CheckResult _checkedThumbnailsParamter = CheckedThumbnailsParamter(originalImagePath, thumbnailPath, isaddwatermark, waterImagePath); if (!_checkedThumbnailsParamter.State) { return(OperatedResult <string> .Fail(_checkedThumbnailsParamter.Message)); } Image _originalImage = Image.FromFile(originalImagePath); int _cutedWidth = specifiedwidth; int _cutedHeight = specifiedheight; int x = 0; int y = 0; int _originalWidth = _originalImage.Width; int _originalHeigh = _originalImage.Height; switch (mode) { case ThumbnailImageCutMode.W: //指定宽,高按比例 _cutedHeight = _originalImage.Height * specifiedwidth / _originalImage.Width; break; case ThumbnailImageCutMode.H: //指定高,宽按比例 _cutedWidth = _originalImage.Width * specifiedheight / _originalImage.Height; break; case ThumbnailImageCutMode.Cut: //指定高宽裁减(不变形) if (_originalImage.Width >= _cutedWidth && _originalImage.Height >= _cutedHeight) { if ((double)_originalImage.Width / (double)_originalImage.Height > (double)_cutedWidth / (double)_cutedHeight) { _originalHeigh = _originalImage.Height; _originalWidth = _originalImage.Height * _cutedWidth / _cutedHeight; y = 0; x = (_originalImage.Width - _originalWidth) / 2; } else { _originalWidth = _originalImage.Width; _originalHeigh = _originalImage.Width * specifiedheight / _cutedWidth; x = 0; y = (_originalImage.Height - _originalHeigh) / 2; } } else { x = (_originalImage.Width - _cutedWidth) / 2; y = (_originalImage.Height - _cutedHeight) / 2; _originalWidth = _cutedWidth; _originalHeigh = _cutedHeight; } break; case ThumbnailImageCutMode.Fit: //不超出尺寸,比它小就不截了,不留白,大就缩小到最佳尺寸,主要为手机用 if (_originalImage.Width > _cutedWidth && _originalImage.Height > _cutedHeight) { if ((double)_originalImage.Width / (double)_originalImage.Height > (double)_cutedWidth / (double)_cutedHeight) { _cutedHeight = _originalImage.Height * specifiedwidth / _originalImage.Width; } else { _cutedWidth = _originalImage.Width * specifiedheight / _originalImage.Height; } } else if (_originalImage.Width > _cutedWidth) { _cutedHeight = _originalImage.Height * specifiedwidth / _originalImage.Width; } else if (_originalImage.Height > _cutedHeight) { _cutedWidth = _originalImage.Width * specifiedheight / _originalImage.Height; } else { _cutedWidth = _originalImage.Width; _cutedHeight = _originalImage.Height; _originalWidth = _cutedWidth; _originalHeigh = _cutedHeight; } break; default: break; } Image _thumbnailImage = new Bitmap(_cutedWidth, _cutedHeight); Graphics _g = SetThumbnailGraphics(_originalImage, _thumbnailImage, _cutedWidth, _cutedHeight, _originalWidth, _originalHeigh, x, y); try { SetThumbnailWaterImage(isaddwatermark, waterImagePath, imagePosition, _g, _cutedWidth, _cutedHeight); EncoderParameters _encoderParams = null; ImageCodecInfo _jpegICI = SetThumbnailImageQuality(quality, out _encoderParams); SaveThumbnailImage(thumbnailPath, _thumbnailImage, _jpegICI, _encoderParams); } catch (Exception ex) { OperatedResult <string> .Fail(string.Format("生成缩略图失败,原因:{0}", ex.Message)); } finally { _originalImage.Dispose(); _thumbnailImage.Dispose(); _g.Dispose(); } return(OperatedResult <string> .Success(string.Format("生成{0}的缩略图成功", originalImagePath), thumbnailPath)); }