Share image plus text via Whatsapp with React Native - javascript

I am working on a react native app and one of my needs is to be able to share via Whatsapp, a png image (created from a svg) plus some text in the message. I have achieved this on Android using react-native-share but when I try it on iOS, the message is populated with the provided text but the image is ignored. I have also tried with Share from react-native but the result is the same.
I have tried this sharing directly a base64 image (data:image/png;base64,image_data) as well as saving the created image and add the path as the url but the result is always the same.
The only way to make this work on iOS (with both react-native-share and Share) is to omit the message, but the text is needed in the requirement.
Is there a way to achieve this?
Versions:
React Native - 0.55.0
react-native-share - 1.1.2
As a side note, the sharing process on Twitter, Email, SMS and some other apps is working correctly.
Code sample:
const base64Data = this.state.uri
const dir = `${RNFS.DocumentDirectoryPath}/tmp_${moment().valueOf()}.png`
RNFS.writeFile(dir, base64Data, 'base64').then(async () => {
const options = {
url: Platform.OS === 'android' ? `file://${dir}` : dir,
message: '' // By omitting the message, whatsapp shows the image
}
try {
await Share.open(options)
// Delete file when share action is completed
await RNFS.unlink(dir)
} catch (error) {
console.log('error', error)
}
}).catch((err) => {
console.log(err.message)
})

Related

How to overcome cors in ionic angular to load json assets from another domain

in our ios application using ionic angular v6 we loads assets files from a seperate server for image file we are not experiencing any corse issue, but for json files ( for lottie animations ) when i provide link i experience cors errors
<span class="analyze_img">
<lottie-player
slot="end"
autoplay
loop
[src]="https://otherdomain.com/male.json"
>
</lottie-player
></span>
to overcome this i used cordova ionic native plugin and loaded the json file seperately
this.http
.get(https://otherdomain.com/male.json, {}, {})
.then((response) => {
console.log('GET RESPONSE ==> ', response);
const data = response.data;
this.lottieFile = data;
console.log('LOTTTIE URL', data);
})
.catch((err) => {
console.log('http err', err);
});
i assigned this variable to lottie-player like below ,
at this time also it is not showing and also the failed to load yellow triangle also missing now?
<span class="analyze_img">
<lottie-player
slot="end"
autoplay
loop
[src]="lottieFile"
>
</lottie-player
></span>
i figured out that the lottifeFile variable isnot pure json object
it is some thing like below ,
//{"v":"5.9.6","fr":30,"ip":0,"op":124,"w":500,"h":500,"nm":"meter scale","ddd":0,"assets":[],"layers"
that is contains escape character, i tried by manually removing this escape character and hardcoding at this time it's working but
programatically removing escape character (response.data.replace(/\/g, '')) not removing here,
is there any alternative way to acheive this?

how can I download and reupload an image in discord.js?

I am trying to repost the content from another bot's message while reposting it in the same way except replacing the image with a thumbnail, but when I delete the original message, the bot doesn't have time to get the image and post it itself. Adding a delay is an ok replacement for now, but I don't want the original message to linger. I've heard of Jimp being used to edit images, so how and where would I apply that to this code? I could simply edit the contrast of the image mildy to repost it. Here is the code
if (message.author.id == botid && message.guild.id == guild4) {
message.embeds.forEach((e) => {
if (e.title !== undefined && e.title.startsWith("The Dungeon ")) {
if (e.image) {
let url = e.image.url;
let desc = e.description;
request(url, async function(err, res, body) {
if (err !== null) return;
imghash
.hash(body)
.then(async (hash) => {
let rareresult = raresdb[hash];
//message.delete(e)
if (rareresult === undefined) {
let result = db[hash];
if (result === undefined) {
embed
.setThumbnail(url)
.setDescription(desc)
await delay(666);
message.delete(e)
return message.channel.send(embed)
}
I am currently using await delay(666); to try and alleviate the issue, but I want the url to be custom that my bot will be able to post on it's own without worrying about how long the previous message stays up. I hope my question is clear
My issue is which the e.image.url or url as i've defined it. Simply reposting that url as the Thumbnail is not good enough since there isn't enough time for it to load if i delete the original message, so I'm looking to upload my own version of that image and use that for .setThumbnail(url). How do I upload and repost an image in discord.s in the context of this code?
Depending on how you want todo this, you have a few choices. You could actually Download and re-upload the images. Or you simply save the URL and re-upload using that URL. (See how to save either)
So then to SEND the image you need to run
message.channel.send({
files:[{
attachment: "<buffer or url>"
}]
});
So for example the following code allowed me to send 2 images using both methods:
const Discord = require("discord.js");
const client = new Discord.Client();
const fs = require("fs");
client.on("ready",() => console.log("Ready"));
client.on("message",function(msg){
if(msg.content === "sendPhotos"){
msg.channel.send({
files:[{
attachment:fs.readFileSync("./DownVote.png"),
name:"DownVote.png"
},{
attachment: "https://cdn.discordapp.com/attachments/679433940615823385/708433102900559933/brave_YnGjgGYqTr.png",
name:"screenie.png"
}]
});
}
});
client.login("token");
The choice of which method is up to you. I recommend however the URL, as this means you won't take up space and have security issues by downloading images.
Don't use delay(666)
Discord.js returns a promise on message.send just send the message and THEN delete the original message.
message.send({embed}).then(function(){ originalMessage.delete() });

React Native - Tesseract.js - Error: Cannot create URL for blob

I am having a problem using the Tesseract.js libary in an React Native App (on the Android Platform). I am currently taking a picture with in the App, saving the image information in a base64 string and trying to pass it the the worker.recognize() function. The string passed to the function is built as followed: data:image/jpeg;base64,MY_BASE64_STRING. I also tried passing a URL to an image and also tried using the absolute path to an image file I'm always getting the same error:
Error: Cannot create URL for blob!
Here is the code I am using for version 2.0.0-alpha.13:
const { TesseractWorker } = Tesseract
const worker = new TesseractWorker({
workerPath: '../../../node_modules/tesseract.js/dist/worker.min.js',
langPath: '../../assets/lang',
corePath: '../../../node_modules/tesseract.js-core/tesseract-core.wasm.js',
})
worker
.recognize(`data:image/jpeg;base64,${data.base64}`)
.progress(info => {
console.log(info)
})
.then(result => {
console.log(result.text)
})
I tried using Versions 1.0.19 and the alpha version 2.0.0-alpha.13
Thank you to you all! ♥
Tesseract.js doesn't support react-native according to this issue.
https://github.com/naptha/tesseract.js/issues/55
Use this library which uses native mobile modules instead. Might not work with expo though
https://github.com/jonathanpalma/react-native-tesseract-ocr

How to fix 'Unexpected token < in JSON at position 0'?

I'm trying to share a website I've done using GitHub pages, but I'm having troubles loading the JSON files.
This is for a friends game server website, using HTML 5, JavaScript and JSON, I've tried running it from localhost and it worked perferctly fine.
The issue actually is a SyntaxError : Unexpected token < in JSON at position 0 and when I try to look for the JSON file in chrome debugger I can't see my JSON files to check where the probleme could be coming from.
The JSON file :
{
"header_menu_games": "Games",
"header_menu_home": "Home",
"header_menu_rules": "Rules",
"header_menu_support": "Support",
"header_serverip_text": "Server ip:",
"header_serverip_copy_btn": "Copy"
}
The JavaScript code I use to translate :
if (isLanguageAvailable) {
var myRequest = new Request(`../../src/lang/${userLang}.json`);
console.info(`User language (${userLang}) is available`);
} else {
var myRequest = new Request("../../src/lang/en.json");
console.info(`The user language (${userLang}) is unfortunately not available`);
}
console.log(myRequest);
fetch(myRequest)
.then(resp => {
resp.json()
.then(data => {
document.getElementById("lang-header_serverip_text").innerHTML = data.header_serverip_text;
})
.catch(err => {
console.error(err);
});
})
.catch(err => {
console.error(err);
});
Console error:
JavaSript catch error:
The full code is available on GitHub.
I believe you're receiving a 404 error because you're pointing your link at the repository location instead of the actual content. You were linking to a nonexistent link: https://vianpyro.github.io/src/lang/en.json
You can do this one of two ways:
Link to the raw version of the file from the repository
Point at the correct location from your friend's domain
1. Linking to the Raw Version
In github, click on Raw and it should open a page containing the actual JSON.
You'll see that the actual link to the content is: https://raw.githubusercontent.com/Vianpyro/Aycraft/master/src/lang/en.json
2. Linking to the hosted location
Part of your original problem was that you weren't pointing at the right path. Your friend's site is hosted at https://vianpyro.github.io/Aycraft and not https://vianpyro.github.io/.
This means that the base url of the site is https://vianpyro.github.io/Aycraft and everything in the path has to follow that. You have to include the /Aycraft after the domain name since that is the baseurl of the site.
The correct url would be:
https://vianpyro.github.io/Aycraft/src/lang/en.json

Electron: how to serve files from appdata

I feel like this is such a basic question but I have been at it for hours and seem to be spinning around the answer. I have an electron app which I also used create-react-app on. I have image files in the appData folder for the electron app and I want to be able to display them in the renderer (using react) using an img tag.
I cannot seem to figure out how to do this. Using an absolute path and file:// for the img src doesn't work. I also tried to register a custom protocol but can't seem to get it to work, I just keep getting file not found (see below). Any ideas or links would be appreciated.
protocol.registerFileProtocol('poster', (request, callback) => {
const url = request.url.substr(9)
console.log(url);
callback({path: app.getPath('appData')+'/posters/'+url})
}, (error) => {
if (error) console.error('Failed to register protocol')
})
The image tag would look something like this:
<img src='poster://test.jpg'/>
What I eventually ended up doing was correcting my original code to use userData instead of appData. I didn't end up solving the part where it was converting to lower case so I just made all of my file names in lower case.
To find the path on your machine where you should put the files you can look at the result of a call to:
app.getPath('userData')
Here is the relevant code in my public/electron.js file:
protocol.registerFileProtocol('poster', (request, callback) => {
const url = request.url.substr(9,request.url.length -10)
callback({path: app.getPath('userData')+'/posters/'+url})
}, (error) => {
if (error) console.error('Failed to register protocol')
})
}
protocol.registerStandardSchemes(['poster'])
In my react code it is just a matter now of prefixing the filename in my image tag with 'poster://' so an image tag looks like:
<img src='poster://poster1.jpg/>

Categories

Resources