AngularJS and BrightCove Media API - angularjs

I am working on integrating BrightCove into an Ionic App (allows HTML and JS/Angular to run as a native app on mobile devices).
The app will play videos and allow user's to download the video to save the user's device, I can get the app to play the video but am having issues getting the
Media API to run the 'find_video_by_id' call.
So I have a download button which triggers the following function
_this.downloadBrightcoveVideo = () => {
let searchParams = {}
BCMAPI.token = 'xxxx..'
BCMAPI.callback = 'useDownloadLink'
BCMAPI.command = 'find_video_by_id'
searchParams.video_id = 1234567890
searchParams.media_delivery = 'HTTP'
searchParams.video_fields = 'FLVURL'
BCMAPI.find (BCMAPI.command, searchParams)
}
where token and video_id are set to my video and URL Access token.
I have tried setting the useDownloadLink function as below
let useDownloadLink = function () { console.log ("I'm Alive") }
or
function useDownloadLink () { console.log ("I'm Alive") }
or
_this. useDownloadLink = () => { console.log ("I'm Alive") }
Every time I run the code I get the error below, even though I have useDownloadLink above the download function
Uncaught ReferenceError: useDownloadLink is not defined
I have tried several variations now and nothing is working, any solution would be gratefully received.
Thanks in advance,
Áine

So after a bit of Google-ing came to the conclusion it was better to use BrightCove's CMS Api to achieve the results I wanted, once going through the api it was actually pretty simple..
Hope that helps someone else :D
Happy Coding!

Related

Handling OAuth with React 18 useEffect hook running twice

Background
I have recently upgraded a fairly sizeable React app to React 18 and for the most part it has been great. One of the key changes is the new double mount in development causing useEffect hooks to all run twice, this is clearly documented in their docs.
I have read their new effect documentation https://beta.reactjs.org/learn/lifecycle-of-reactive-effects and although it is quite detailed there is a use case I believe I have found which is not very well covered.
The issue
Essentially the issue I have run into is I am implementing OAuth integration with a third-party product. The flow:
-> User clicks create integration -> Redirect to product login -> Gets redirected back to our app with authorisation code -> We hit our API to finalise the integration (HTTP POST request)
The problem comes now that the useEffect hook runs twice it means that we would hit this last POST request twice, first one would succeed and the second would fail because the integration is already setup.
This is not potentially a major issue but the user would see an error message even though the request worked and just feels like a bad pattern.
Considered solutions
Refactoring to use a button
I could potentially get the user to click a button on the redirect URL after they have logged into the third-party product. This would work and seems to be what the React guides recommend (Although different use case they suggested - https://beta.reactjs.org/learn/you-might-not-need-an-effect#sharing-logic-between-event-handlers).
The problem with this is that the user has already clicked a button to create the integration so it feels like a worse user experience.
Ignore the duplicate API call
This issue is only a problem in development however it is still a bit annoying and feels like an issue I want to explore further
Code setup
I have simplified the code for this example but hopefully this gives a rough idea of how the intended code is meant to function.
const IntegrationRedirect: React.FC = () => {
const navigate = useNavigate();
const organisationIntegrationsService = useOrganisationIntegrationsService();
// Make call on the mount of this component
useEffect(() => {
// Call the method
handleCreateIntegration();
}, []);
const handleCreateIntegration = async (): Promise<void> => {
// Setup request
const request: ICreateIntegration = {
authorisationCode: ''
};
try {
// Make service call
const setupIntegrationResponse = await organisationIntegrationsService.createIntegration(request);
// Handle error
if (setupIntegrationResponse.data.errors) {
throw 'Failed to setup integrations';
}
// Navigate away on success
routes.organisation.integrations.navigate(navigate);
}
catch (error) {
// Handle error
}
};
return ();
};
What I am after
I am after suggestions based on the React 18 changes that would handle this situation, I feel that although this is a little specific/niche it is still a viable use case. It would be good to have a clean way to handle this as OAuth integration is quite a common flow for integration between products.
You can use the useRef() together with useEffect() for a workaround
const effectRan = useRef(false)
useEffect(() => {
if (effectRan.current === false) {
// do the async data fetch here
handleCreateIntegration();
}
//cleanup function
return () => {
effectRan.current = true // this will be set to true on the initial unmount
}
}, []);
This is a workaround suggested by Dave Gray on his youtube channel https://www.youtube.com/watch?v=81faZzp18NM

Application insights app.js and vendor.js

I'm implementing Application Insights to our AngularJS application.
We've already setup some kind of logic to track the loading times for API calls.
I was wondering if it is possible to track the loading times of the app.js and vendor.js files.
Do you guys know if this is possible?
Thank you in advance!
I was wondering if it is possible to track the loading times of the app.js and vendor.js files.
According to ApplicationInsights-JS, to get the page loading time, you can use pageView.properties.duration , try the following code snippet taken from the document:
_self.trackPageView = (pageView?: IPageViewTelemetry, customProperties?: ICustomProperties) => {
try {
let inPv = pageView || {};
_pageViewManager.trackPageView(inPv, {...inPv.properties, ...inPv.measurements, ...customProperties});
if (_self.config.autoTrackPageVisitTime) {
_pageVisitTimeManager.trackPreviousPageVisit(inPv.name, inPv.uri);
}
} catch (e) {
_throwInternal(
eLoggingSeverity.CRITICAL,
_eInternalMessageId.TrackPVFailed,
"trackPageView failed, page view will not be collected: " + getExceptionName(e),
{ exception: dumpObj(e) });
}
};
You can refer to Capture and view page load times in your Azure web app with Application Insights and PageViewPerformanceManager.ts

Smart Contract function not working on ReactJS but working properly on Remix IDE

I'm a new Web3 Developer and working on a personal DAPP.I have tested all functions of the smart contract in remix but the function mentioned below is not properly working in my react app. I have also tested all other function of the smart contract in my react app and they all are working fine except this one :
//Smart contract function which is not working properly on the front end
function tipPost(uint _index,uint _tipAmount) public payable {
uint id = _index;
Tweeter storage tweet = tweets[id];
require(_tipAmount > 0);
_tipAmount = msg.value;
(bool sent,) = tweet.author.call{value: _tipAmount}("");
require(sent, "Failed to send Ether");
tweet.tipAmount = tweet.tipAmount + _tipAmount;
emit PostTipped( id,tweet.tipAmount, payable(msg.sender));
}
//function created in React App
async function TipTweet(index) {
if (!tip) {
return;
}
//Provider,signer has been already defined
const response = await contract.tipPost(index, tip);
await response.wait();
console.log("Tipped");
setTip(0);
// setIsOpen(false);
}
Whenever I execute this function in my react app,I am able to make a transaction using metamask but this only console logs me "Tipped" and it doesn't even gives me any errors on the console so I don't know what to do. Maybe the way I am interacting with this function is not correct but the rest of the functions are working perfectly fine through this method .Your help would be appreciated!

React native axios crashing and werid behaviour

Axios is behaving weird on my react native webview if you have any idea how to solve or how i can track the problem it would be of much help.
On the onMessage of the webview i recieve the html of the website so i can get a specific link. I send the message when the user taps anywhere on screen.
Injected js:
var body_of_html = document.body;
body_of_html.addEventListener('click',function(e){
window.ReactNativeWebView.postMessage(document.documentElement.innerHTML)
},false);
Case 1
This doesnt console.log anything and after some time crashes the app.
onMessage={event => {
// console.log('asdas');
var regex = new RegExp('token=[a-zA-z0-9]+');
if (event.nativeEvent.data.toString().match(regex) != null) {
let asd =
'https://fvs.io/redirector?' +
event.nativeEvent.data.toString().match(regex);
axios.get(asd).then(rs => {
console.log(rs);
});
Case 2
This one works perfectly fine and logs "Anything".
onMessage={event => {
var regex = new RegExp('token=[a-zA-z0-9]+');
if (event.nativeEvent.data.toString().match(regex) != null) {
let asd =
'https://fvs.io/redirector?' +
event.nativeEvent.data.toString().match(regex);
axios.get(asd).then(console.log("Anything"));
As you can see from the above cases i am unable to get the response from the axios call. Which always after some time crashes the app. Am i doing something wrong on reciving the response ?
Edit: I think I know what might have caused my application to crash but this is just what I found after looking at the data consumed. The link i was sending to the axios.get was retriving bits of a video until it fully buffered. But the way my code was , it would do this action each time i tapped the screen. I guess at some point axios couldnt handle reciving 10x + videos at 1080p at the same time. Just to clarify my intention was just to get the redirection link i didnt know it would cause the video to buffer.
As in all promises, in order to debug the error, e.g. in cases where event.nativeEvent.data may be undefined, causing .toString() to throw error, use a catch block.
axios.get(asd).then(rs => {
console.log(rs);
}).catch(error => console.log("error from axios", error))

Pdf Tron error " Exception error: Pdf error not found" (React App)

I'm trying to embed Pdf tron to my React application. I'm receiving this error when I'm clicking on the tab I want to filter to find the relative pdf file.
const handleFilteredDocs = (id)=>{
const filteredDoc = props.location.documents && props.location.documents.filter(doc=>{
return doc.controlId === id
})
setFileteredDoc(filteredDoc)
setPdfPath(filteredDoc[0].filePath)
WebViewer(
{
path: 'lib',
initialDoc: `lib/pdf/${pdfPath}`,
extension: "pdf"
},
viewer.current,
).then((instance) => {
const { docViewer, Annotations } = instance;
const annotManager = docViewer.getAnnotationManager();
docViewer.on('documentLoaded', () => {
const rectangleAnnot = new Annotations.RectangleAnnotation();
rectangleAnnot.PageNumber = 1;
// values are in page coordinates with (0, 0) in the top left
rectangleAnnot.X = 100;
rectangleAnnot.Y = 150;
rectangleAnnot.Width = 200;
rectangleAnnot.Height = 50;
rectangleAnnot.Author = annotManager.getCurrentUser();
annotManager.addAnnotation(rectangleAnnot);
// need to draw the annotation otherwise it won't show up until the page is refreshed
annotManager.redrawAnnotation(rectangleAnnot);
});
});
}
I'm thinking is because the ref component didn't receive in time the pdfPath state and then throw the error. I've tried to place a separate button to load the pdf with the pdfPath correctly updated and in that case worked. What can i do make it render correctly there?
this is the error I get from the console:
(index)
Value
UI version "7.3.0"
Core version "7.3.0"
Build "Mi8yMi8yMDIxfDZmZmNhOTdmMQ=="
WebViewer Server false
Full API false
Object
CoreControls.js:189 Could not use incremental download for url /lib/pdf/. Reason: The file is not linearized.
CoreControls.js:189
{message: "The file is not linearized."}
CoreControls.js:189 There may be some degradation of performance. Your server has not been configured to serve .gz. and .br. files with the expected Content-Encoding. See http://www.pdftron.com/kb_content_encoding for instructions on how to resolve this.
CoreControls.js:189 There may be some degradation of performance. Your server has not been configured to serve .gz. and .br. files with the expected Content-Encoding. See http://www.pdftron.com/kb_content_encoding for instructions on how to resolve this.
CoreControls.js:189 There may be some degradation of performance. Your server has not been configured to serve .gz. and .br. files with the expected Content-Encoding. See http://www.pdftron.com/kb_content_encoding for instructions on how to resolve this.
81150ece-4c18-41b0-b551-b92f332bd17f:1
81150ece-4c18-41b0-b551-b92f332bd17f:1 PDFNet is running in demo mode.
81150ece-4c18-41b0-b551-b92f332bd17f:1 Permission: read
CoreControls.js:922 Uncaught (in promise)
{message: "Exception: ↵ Message: PDF header not found. The f… Function : SkipHeader↵ Linenumber : 1139↵", type: "InvalidPDF"}
Thank you guys for any help I will get on this!
The value of "pdfPath" isn't set to "filteredDoc[0].filePath" yet after you call "setPdfPath" (it'll still be the initial state till the next render). One thing you can do is pass a callback function when using "setState" to call "WebViewer()" after "pdfPath" has been updated
https://reactjs.org/docs/react-component.html#setstate
Also there is a guide on how to add PDFtron to a React project in the following link
https://www.pdftron.com/documentation/web/get-started/react/
One thing to note, is it's does the following
useEffect(() => {
// will only run once
WebViewer()
}, [])
By doing the above, "WebViewer" is only initialized once. It might be a good idea to do something similar and use "loadDocument" (https://www.pdftron.com/documentation/web/guides/best-practices/#loading-documents-with-loaddocument) when switching between documents instead of reinitializing WebViewer each time the state changes

Resources