Skip to content

Conversation

@ArgoZhang
Copy link
Member

@ArgoZhang ArgoZhang commented Dec 25, 2025

Link issues

fixes #866

Summary By Copilot

Regression?

  • Yes
  • No

Risk

  • High
  • Medium
  • Low

Verification

  • Manual (required)
  • Automated

Packaging changes reviewed?

  • Yes
  • No
  • N/A

☑️ Self Check before Merge

⚠️ Please check all items below before review. ⚠️

  • Doc is updated/provided or not needed
  • Demo is updated/provided or not needed
  • Merge the latest code from the main branch

Summary by Sourcery

Add client-side support for starting and stopping HikVision video recording and expose it through the Blazor component API.

New Features:

  • Add JavaScript helpers to start and stop HikVision video recording when a real-time stream is active.
  • Expose StartRecord and StopRecord methods on the HikVisionWebPlugin Blazor component to control recording from .NET code.

Enhancements:

  • Log exceptions during capture and download operations in the HikVision JavaScript module for easier debugging.
  • Clarify XML documentation for capture methods to better describe behavior and return types.

Copilot AI review requested due to automatic review settings December 25, 2025 05:26
@bb-auto bb-auto bot added the enhancement New feature or request label Dec 25, 2025
@bb-auto bb-auto bot added this to the v9.2.0 milestone Dec 25, 2025
@sourcery-ai
Copy link

sourcery-ai bot commented Dec 25, 2025

Reviewer's Guide

Adds client- and server-side support for starting and stopping HikVision video recording, wires new JS interop calls through the Razor component, and slightly improves error handling and documentation for capture operations.

Sequence diagram for starting and stopping HikVision recording via JS interop

sequenceDiagram
    participant CSharp_HikVisionWebPlugin
    participant JS_HikVisionWebPlugin as JS_HikVisionWebPlugin_razor_js
    participant JS_Hikvision as hikvision_js
    participant WebVideoCtrl

    CSharp_HikVisionWebPlugin->>CSharp_HikVisionWebPlugin: StartRecord()
    alt IsLogin_and_IsRealPlaying_true
        CSharp_HikVisionWebPlugin->>JS_HikVisionWebPlugin: InvokeAsync startRecord Id
        JS_HikVisionWebPlugin->>JS_Hikvision: startRecord Id
        JS_Hikvision->>JS_Hikvision: Data.get Id
        JS_Hikvision->>JS_Hikvision: check realPlaying
        alt realPlaying_true
            JS_Hikvision->>WebVideoCtrl: I_StartRecord record_timestamp
            WebVideoCtrl-->>JS_Hikvision: success_or_error_callback
            JS_Hikvision->>JS_Hikvision: resolve_or_reject_Promise
            JS_Hikvision-->>JS_HikVisionWebPlugin: bool_result
            JS_HikVisionWebPlugin-->>CSharp_HikVisionWebPlugin: bool_result
        else realPlaying_not_true
            JS_Hikvision-->>JS_HikVisionWebPlugin: false
            JS_HikVisionWebPlugin-->>CSharp_HikVisionWebPlugin: false
        end
    else not_logged_in_or_not_playing
        CSharp_HikVisionWebPlugin-->>CSharp_HikVisionWebPlugin: return_false
    end

    CSharp_HikVisionWebPlugin->>CSharp_HikVisionWebPlugin: StopRecord()
    alt IsLogin_and_IsRealPlaying_true
        CSharp_HikVisionWebPlugin->>JS_HikVisionWebPlugin: InvokeAsync stopRecord Id
        JS_HikVisionWebPlugin->>JS_Hikvision: stopRecord Id
        JS_Hikvision->>JS_Hikvision: Data.get Id
        JS_Hikvision->>JS_Hikvision: check realPlaying
        alt realPlaying_true
            JS_Hikvision->>WebVideoCtrl: I_StopRecord
            WebVideoCtrl-->>JS_Hikvision: success_or_error_callback
            JS_Hikvision->>JS_Hikvision: resolve_or_reject_Promise
            JS_Hikvision-->>JS_HikVisionWebPlugin: bool_result
            JS_HikVisionWebPlugin-->>CSharp_HikVisionWebPlugin: bool_result
        else realPlaying_not_true
            JS_Hikvision-->>JS_HikVisionWebPlugin: false
            JS_HikVisionWebPlugin-->>CSharp_HikVisionWebPlugin: false
        end
    else not_logged_in_or_not_playing
        CSharp_HikVisionWebPlugin-->>CSharp_HikVisionWebPlugin: return_false
    end
Loading

Class diagram for updated HikVisionWebPlugin recording and capture methods

classDiagram
    class HikVisionWebPlugin {
        bool IsLogin
        bool IsRealPlaying
        string Id

        Task CapturePictureAndDownload()
        Task~IJSStreamReference?~ CapturePicture(CancellationToken token)
        Task TriggerReceivePictureStream(IJSStreamReference stream)
        Task~bool~ StartRecord()
        Task~bool~ StopRecord()
    }

    class Hikvision_razor_js {
        +init(id, invoke)
        +login(id, ip, port, userName, password, loginType)
        +logout(id)
        +startRealPlay(id)
        +stopRealPlay(id)
        +openSound(id)
        +closeSound(id)
        +setVolume(id, value)
        +capturePicture(id)
        +capturePictureAndDownload(id)
        +startRecord(id)
        +stopRecord(id)
        +dispose(id)
    }

    class hikvision_js {
        +startRecord(id)
        +stopRecord(id)
        +capturePicture(id)
        +capturePictureAndDownload(id)
        +dispose(id)
    }

    HikVisionWebPlugin --> Hikvision_razor_js : uses_JS_interop
    Hikvision_razor_js --> hikvision_js : wraps_calls
    hikvision_js --> WebVideoCtrl : calls_recording_APIs

    class WebVideoCtrl {
        +I_StartRecord(recordName, options)
        +I_StopRecord(options)
    }
Loading

File-Level Changes

Change Details Files
Add JS-side helpers to start and stop recording using the HikVision WebVideoCtrl API with promise-based completion.
  • Introduce startRecord(id) that validates real-time play state, calls WebVideoCtrl.I_StartRecord, and resolves/rejects a promise based on async callbacks.
  • Introduce stopRecord(id) that validates real-time play state, calls WebVideoCtrl.I_StopRecord, and resolves/rejects a promise based on async callbacks.
  • Log exceptions to the console in capturePicture and capturePictureAndDownload to aid debugging.
src/components/BootstrapBlazor.HikVision/wwwroot/hikvision.js
Expose recording operations through the HikVisionWebPlugin component via JS interop and update related documentation comments.
  • Update XML documentation for CapturePictureAndDownload and CapturePicture to more accurately describe behavior and return types.
  • Add StartRecord() method that checks login and real-play state before invoking JS startRecord via InvokeAsync.
  • Add StopRecord() method that checks login and real-play state before invoking JS stopRecord via InvokeAsync.
src/components/BootstrapBlazor.HikVision/Components/HikVisionWebPlugin.razor.cs
Wire new recording functions through the HikVisionWebPlugin JS shim so they can be invoked from .NET.
  • Import startRecord and stopRecord from hikvision.js in the Razor JS shim.
  • Re-export startRecord and stopRecord so they are available to the component interop surface.
src/components/BootstrapBlazor.HikVision/Components/HikVisionWebPlugin.razor.js

Assessment against linked issues

Issue Objective Addressed Explanation
#866 Add an IsOpenSound parameter to the HikVision component (and any necessary wiring through JS/logic) so that sound playback can be controlled via this parameter. The PR adds recording-related methods (startRecord, stopRecord) and some minor logging and documentation changes, but it does not introduce an IsOpenSound parameter in the component, its JS interop, or anywhere else in the codebase.

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@ArgoZhang ArgoZhang merged commit 81271e6 into master Dec 25, 2025
6 of 7 checks passed
@ArgoZhang ArgoZhang deleted the dev-hik branch December 25, 2025 05:26
Copy link

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - I've found 3 issues, and left some high level feedback:

  • In startRecord/stopRecord the polling handle is created with setInterval but cleared with clearTimeout; this should be clearInterval to avoid leaking the interval timer.
  • startRecord/stopRecord return a Promise that never settles if WebVideoCtrl.I_StartRecord/I_StopRecord throw before setting completed, so consider rejecting the Promise in the catch block or short‑circuiting to a resolved value there.
  • The stopRecord catch block is empty while other operations log exceptions with console.log, so it would be more consistent and aid debugging to log or otherwise handle the error there as well.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- In `startRecord`/`stopRecord` the polling handle is created with `setInterval` but cleared with `clearTimeout`; this should be `clearInterval` to avoid leaking the interval timer.
- `startRecord`/`stopRecord` return a Promise that never settles if `WebVideoCtrl.I_StartRecord`/`I_StopRecord` throw before setting `completed`, so consider rejecting the Promise in the `catch` block or short‑circuiting to a resolved value there.
- The `stopRecord` catch block is empty while other operations log exceptions with `console.log`, so it would be more consistent and aid debugging to log or otherwise handle the error there as well.

## Individual Comments

### Comment 1
<location> `src/components/BootstrapBlazor.HikVision/wwwroot/hikvision.js:496-498` </location>
<code_context>
     }
+
+    return new Promise((resolve, reject) => {
+        const handler = setInterval(() => {
+            if (completed) {
+                clearTimeout(handler);
+                if (error === null) {
+                    resolve(true);
</code_context>

<issue_to_address>
**issue (bug_risk):** Use `clearInterval` instead of `clearTimeout` for an interval handle.

`setInterval` must be paired with `clearInterval` for the returned handle. Using `clearTimeout` here is incorrect and risks the interval not being cleared, causing ongoing executions and potential leaks after the Promise has settled.
</issue_to_address>

### Comment 2
<location> `src/components/BootstrapBlazor.HikVision/wwwroot/hikvision.js:495-504` </location>
<code_context>
+        console.log(ex);
     }
+
+    return new Promise((resolve, reject) => {
+        const handler = setInterval(() => {
+            if (completed) {
+                clearTimeout(handler);
+                if (error === null) {
+                    resolve(true);
+                }
+                else {
+                    reject(error);
+                }
+            }
+        }, 16);
+    });
+}
</code_context>

<issue_to_address>
**suggestion:** Consider resolving/rejecting directly from the success/error callbacks instead of polling with `setInterval`.

Because `I_StartRecord`/`I_StopRecord` already take `success` and `error` callbacks, you can wrap them in a Promise and call `resolve(true)` / `reject(oError)` directly in those callbacks. This removes the `completed`/`error` state and the 16ms `setInterval`, simplifying the flow and avoiding an extra timer altogether.
</issue_to_address>

### Comment 3
<location> `src/components/BootstrapBlazor.HikVision/wwwroot/hikvision.js:470` </location>
<code_context>
+    }
+}
+
+export async function startRecord(id) {
+    const vision = Data.get(id);
+    const { realPlaying } = vision;
</code_context>

<issue_to_address>
**issue (complexity):** Consider simplifying the new startRecord/stopRecord implementations by resolving the Promise directly in the SDK callbacks (optionally via a shared helper) instead of using polling flags and intervals.

You can simplify `startRecord`/`stopRecord` by removing the polling/flags and resolving the promise directly in the callbacks. This keeps all behavior while reducing complexity and duplication, and also fixes the `clearTimeout`/`setInterval` mismatch.

```js
export function startRecord(id) {
    const vision = Data.get(id);
    const { realPlaying } = vision;

    if (realPlaying !== true) {
        return Promise.resolve(false);
    }

    return new Promise((resolve, reject) => {
        try {
            WebVideoCtrl.I_StartRecord(`record_${Date.now()}`, {
                success: () => resolve(true),
                error: (oError) => reject(oError)
            });
        } catch (ex) {
            console.log(ex);
            reject(ex);
        }
    });
}
```

```js
export function stopRecord(id) {
    const vision = Data.get(id);
    const { realPlaying } = vision;

    if (realPlaying !== true) {
        return Promise.resolve(false);
    }

    return new Promise((resolve, reject) => {
        try {
            WebVideoCtrl.I_StopRecord({
                success: () => resolve(true),
                error: (oError) => reject(oError)
            });
        } catch (ex) {
            console.log(ex);
            reject(ex);
        }
    });
}
```

If you want to further reduce duplication, you can extract a tiny helper:

```js
function execRecord(fn) {
    return new Promise((resolve, reject) => {
        try {
            fn({
                success: () => resolve(true),
                error: (oError) => reject(oError)
            });
        } catch (ex) {
            console.log(ex);
            reject(ex);
        }
    });
}

// usage
export function startRecord(id) {
    const vision = Data.get(id);
    if (vision.realPlaying !== true) return Promise.resolve(false);
    return execRecord((opts) => WebVideoCtrl.I_StartRecord(`record_${Date.now()}`, opts));
}

export function stopRecord(id) {
    const vision = Data.get(id);
    if (vision.realPlaying !== true) return Promise.resolve(false);
    return execRecord((opts) => WebVideoCtrl.I_StopRecord(opts));
}
```

This removes the interval-based busy-wait, unifies error handling (always logs and rejects on exceptions/errors), and keeps the external behavior (`true` on success, rejection on failure, `false` when not playing) intact.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Copy link

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR adds video recording functionality to the HikVision component, despite the misleading title which mentions "IsOpenSound parameter". The changes introduce StartRecord and StopRecord methods across JavaScript and C# layers.

Key changes:

  • Added startRecord and stopRecord functions in JavaScript to interface with WebVideoCtrl API
  • Exposed these functions through C# wrapper methods for Blazor integration
  • Updated documentation comments for capture methods
  • Bumped package version from 10.0.6 to 10.0.7

Reviewed changes

Copilot reviewed 4 out of 4 changed files in this pull request and generated 3 comments.

File Description
hikvision.js Added startRecord and stopRecord async functions with callback-to-promise conversion, plus console logging in catch blocks
HikVisionWebPlugin.razor.js Added imports and exports for new startRecord and stopRecord functions
HikVisionWebPlugin.razor.cs Implemented C# wrapper methods StartRecord and StopRecord, updated documentation comments
BootstrapBlazor.HikVision.csproj Incremented version from 10.0.6 to 10.0.7
Comments suppressed due to low confidence (4)

src/components/BootstrapBlazor.HikVision/wwwroot/hikvision.js:1

  • Unused import registerBootstrapBlazorModule.
import { addScript, registerBootstrapBlazorModule } from '../BootstrapBlazor/modules/utility.js';

src/components/BootstrapBlazor.HikVision/wwwroot/hikvision.js:76

  • Unused variable originalDestroy.
    const originalDestroy = JSVideoPlugin.prototype.JS_DestroyPlugin;

src/components/BootstrapBlazor.HikVision/wwwroot/hikvision.js:190

  • Unused variable logined.
    const { szDeviceIdentify, logined } = vision;

src/components/BootstrapBlazor.HikVision/wwwroot/hikvision.js:390

  • Unused variable iWndIndex.
    const { iWndIndex, realPlaying } = vision;

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

});
}
catch (ex) {

Copy link

Copilot AI Dec 25, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The catch block is empty and doesn't log the exception like other catch blocks in this file. For consistency with the error handling pattern used in lines 428, 466, and 492, this should log the exception.

Suggested change
console.error('Error while stopping record:', ex);

Copilot uses AI. Check for mistakes.
return new Promise((resolve, reject) => {
const handler = setInterval(() => {
if (completed) {
clearTimeout(handler);
Copy link

Copilot AI Dec 25, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Using clearTimeout with a setInterval handler is incorrect. The handler is created by setInterval on line 496, so it should be cleared using clearInterval, not clearTimeout.

Copilot uses AI. Check for mistakes.
return new Promise((resolve, reject) => {
const handler = setInterval(() => {
if (completed) {
clearTimeout(handler);
Copy link

Copilot AI Dec 25, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Using clearTimeout with a setInterval handler is incorrect. The handler is created by setInterval on line 536, so it should be cleared using clearInterval, not clearTimeout.

Suggested change
clearTimeout(handler);
clearInterval(handler);

Copilot uses AI. Check for mistakes.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat(HikVision): add IsOpenSound parameter

2 participants