Drop-down options filled from json file in Meteor - json

I have a local json file in my client folder that contains information for <option>s in a <select> tag.
I tried using ajax to fill up <option>s but my app keeps crashing.
What is the proper way to get information out of a local json file in meteor?

To get information from the server you need to use a Meteor method.
To read local file you need to use assets.
For example, assuming your file is /private/options.json:
server side
Meteor.methods({
getOptions: function() {
return Assets.getText('options.json');
},
});
client side
var loadOptions = function() {
Meteor.call('getOptions', function(error, result){
fillOptions(JSON.parse(result));
});
};

I had the same problem, I needed to load labels for the client.
Instead of calling the server, the client can directly perform a HTTP call and retrieve the file.
Put your file into the public directory
Use the HTTP API to get your file
HTTP.get('/yourFile.json', {}, function(error, result) {
var parsedFile = JSON.parse(result.content);
});
If you are using Iron router be sure to wait for the result before displaying your page with a waitOn.
As the call is asynchronous, it might take some time to get your result.

Related

Snapchat download all memories at once

Over the years on snapchat I have saved lots of photos that I would like to retrieve now, The problem is they do not make it easy to export, but luckily if you go online you can request all the data (thats great)
I can see all my photos download link and using the local HTML file if I click download it starts downloading.
Here's where the tricky part is, I have around 15,000 downloads I need to do and manually clicking each individual one will take ages, I've tried extracting all of the links through the download button and this creates lots of Urls (Great) but the problem is, if you past the url into the browser then ("Error: HTTP method GET is not supported by this URL") appears.
I've tried a multitude of different chrome extensions and none of them show the actually download, just the HTML which is on the left-hand side.
The download button is a clickable link that just starts the download in the tab. It belongs under Href A
I'm trying to figure out what the best way of bulk downloading each of these individual files is.
So, I just watched their code by downloading my own memories. They use a custom JavaScript function to download your data (a POST request with ID's in the body).
You can replicate this request, but you can also just use their method.
Open your console and use downloadMemories(<url>)
Or if you don't have the urls you can retrieve them yourself:
var links = document.getElementsByTagName("table")[0].getElementsByTagName("a");
eval(links[0].href);
UPDATE
I made a script for this:
https://github.com/ToTheMax/Snapchat-All-Memories-Downloader
Using the .json file you can download them one by one with python:
req = requests.post(url, allow_redirects=True)
response = req.text
file = requests.get(response)
Then get the correct extension and the date:
day = date.split(" ")[0]
time = date.split(" ")[1].replace(':', '-')
filename = f'memories/{day}_{time}.mp4' if type == 'VIDEO' else f'memories/{day}_{time}.jpg'
And then write it to file:
with open(filename, 'wb') as f:
f.write(file.content)
I've made a bot to download all memories.
You can download it here
It doesn't require any additional installation, just place the memories_history.json file in the same directory and run it. It skips the files that have already been downloaded.
Short answer
Download a desktop application that automates this process.
Visit downloadmysnapchatmemories.com to download the app. You can watch this tutorial guiding you through the entire process.
In short, the app reads the memories_history.json file provided by Snapchat and downloads each of the memories to your computer.
App source code
Long answer (How the app described above works)
We can iterate over each of the memories within the memories_history.json file found in your data download from Snapchat.
For each memory, we make a POST request to the URL stored as the memories Download Link. The response will be a URL to the file itself.
Then, we can make a GET request to the returned URL to retrieve the file.
Example
Here is a simplified example of fetching and downloading a single memory using NodeJS:
Let's say we have the following memory stored in fakeMemory.json:
{
"Date": "2022-01-26 12:00:00 UTC",
"Media Type": "Image",
"Download Link": "https://app.snapchat.com/..."
}
We can do the following:
// import required libraries
const fetch = require('node-fetch'); // Needed for making fetch requests
const fs = require('fs'); // Needed for writing to filesystem
const memory = JSON.parse(fs.readFileSync('fakeMemory.json'));
const response = await fetch(memory['Download Link'], { method: 'POST' });
const url = await response.text(); // returns URL to file
// We can now use the `url` to download the file.
const download = await fetch(url, { method: 'GET' });
const fileName = 'memory.jpg'; // file name we want this saved as
const fileData = download.body; // contents of the file
// Write the contents of the file to this computer using Node's file system
const fileStream = fs.createWriteStream(fileName);
fileData.pipe(fileStream);
fileStream.on('finish', () => {
console.log('memory successfully downloaded as memory.jpg');
});

Redirect in express

I am using express and I would like to redirect to another file since my server is not always up and running. I can not understand why I am receiving a HTML document when my file is JSON. It looks like it gets redirected, but the result is wrong. I can see that my page is redirected from the old URL to the new URL. So it looks like that part is working. But I am not receiving my local json-file in the response.
What I have in my server index.js file:
app.use('/my/original/url', (req, res) => {
res.writeHead(302, { location: '/mock/mockedresult.json' });
res.end();
});
I found out that I need to make my mock folder available. I did so by adding this line of code above the code snippet in my question:
app.use('/mock', express.static(resolve(process.cwd(), 'server/mock')));

Read file at startup Chrome extension/kiosk app

I'm currently developing my first Chrome app that we'll be used as a Kiosk app later.
I'm trying to read a file at the startup of the app, that file is a config file (.json). It contains values that will be passed inside a URL once the app has launched (ie: www.google.com/key=keyValueInTheJsonFile).
I used https://developer.chrome.com/apps/fileSystem (the method "chooseEntry" especially) to be able to read a file, but in my case I would like to directly specify the path/name of the file and not ask the user to select a file. Like that I can pass the values to the redirected URL at the startup.
Any idea of how I could possibly do that?
Thanks!
If your file is in the package you can read it using simple XHR or Fetch.
You can't use web filesystem since it has different purpose and Chrome filesystem (user's FS) won't work here either since it needs a user interaction.
Use function getURL to get a full URL to the resource and then make XHR call:
var rUrl = chrome.runtime.getURL('file.json');
fetch(rUrl).then((response) => {
return response.json();
})
.then((fileContent) => {
// the content
})
.catch((cause) => console.log(cause));

Create Action For Running Nodejs inside HTML

I am new at Node.js
I create a server with node.js I have file like this:
Server.js
Client.js
Index.html
Server configuration is okay. But Inside HTML, I would like to link or an action to run client.js
At HTML, usually we use Link to link a page.
or
run npm with node client.js to run client.js
How I do it at html to run client.js, so if we click a link - client.js will run (the action is same like we do for run at npm node client.js)?
EDIT :
Oke, it looks like difficult to run client.js inside html with click. I changed my question.
I run node.js. And I open a browser (with anything extension html or js) and I would like to run client.js with a click. How do I do that?
I have never hear of such thing.
But I think, if you want to change something in server through frontend, http ajax is a good way.
But according to my acquaintance, when server accept a request from frontend, in a general way,it will run some code,such as function, but not js file.
You could run js file through child_process, it is a module in node, which use to call the shell in your system.
PS, shell.js is a better way if you want to call the shell in nodejs.
see this. https://github.com/shelljs/shelljs
Some server side programming environments work on the basis of having a program, in a file, for each URL that needs to be handled.
Node.js does not work that way.
You write a single server program which handles all the requests and which examines the URL of each one to determine what to do.
const http = require('http');
const server = http.createServer((req, res) => {
console.log(req.url);
if (req.url == "/") {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end("The homepage");
} else if (req.url == "/client.js") {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end("Whatever you want to do for a request for client.js");
} else {
res.writeHead(404, {'Content-Type': 'text/plain'});
res.end("Not found");
}
});
server.on('clientError', (err, socket) => {
socket.end('HTTP/1.1 400 Bad Request\r\n\r\n');
});
server.listen(8000);
While you might store some code in client.js, that filename wouldn't be mentioned to the client. The server would just load it like any other module and then conditionally call functions from it.

Dojo 1.9 JsonRest remote url on a different server

I'm trying to get dojo to show Json data that comes from a remote web service. I need to be clear though - the web server hosting the html/dojo page I access isn't the same server as the one that's running the web service that returns the json data - the web service server just can't serve html pages reliably (don't ask!!).
As a test I move the page into the same web server as the web service and the below works. As soon as I move it back so that the html/dojo is served from Apache (//myhost.nodomain:82 say) and the web service sending the json is "{target:http://myhost.nodomain:8181}", then it stops working.
I've used FFox to look at the network & I see the web service being called ok, the json data is returned too & looks correct (I know it is from the previous test), but the fields are no longer set. I've tried this with DataGrid and the plain page below with the same effects.
Am I tripping up over something obvious???
Thanks
require([
"dojo/store/JsonRest",
"dojo/store/Memory",
"dojo/store/Cache",
"dojox/grid/DataGrid",
"dojo/data/ObjectStore",
"dojo/query",
"dojo/domReady!"
],
function(JsonRest, Memory, Cache, DataGrid, ObjectStore, query) {
var myStore, dataStore, grid;
myStore = JsonRest(
{
target: "http://localhost:8181/ws/job/definition/",
idProperty: "JOB_NAME"
}
);
myStore.query("JOB00001"
).then(function(results) {
var theJobDef = results[0];
dojo.byId("JOB_NAME").innerHTML = theJobDef.JOB_NAME;
dojo.byId("SCHEDULED_DAYS").innerHTML = theJobDef.SCHEDULED_DAYS;
});
}
);
Its true what Frans said about the cross domain restriction but dojo has this link to work around the problem.
require(["dojo/request/iframe"], function(iframe){
iframe("something.xml", {
handleAs: "json"
}).then(function(xmldoc){
// Do something with the XML document
}, function(err){
// Handle the error condition
});
// Progress events are not supported using the iframe provider
});
you can simply use this and the returned data can be inserted into a store and then into the grid.
Are you familiar with the Same Origin Policy:
http://en.wikipedia.org/wiki/Same-origin_policy
Basically it restricts websites to do AJAX requests to other domains than the html page was loaded from. Common solutions to overcome this are CORS and JSON-P. However, remember that these restrictions are made for security reasons.