Permanent shared url in box api - box-api

My requirement
One user uploads the file to box from my application using API and other users should be able to see that file as a link in my application.
Im not getting the shared url at the time of upload. And from the document, I understood that the shared url expires soon. Is it possible to get a permanent url to access file by other users (without login to box) ?

Shared links aren't automatically created when you upload a file. You need to make a request to the API to create one. You can find the documentation for how to do that here - https://developers.box.com/docs/#files-create-a-shared-link-for-a-file.
If you set the access field to open and leave the unshared_at time empty, then you'll get a link that anyone can access and that won't expire.
For example, your request might look like:
PUT https://api.box.com/2.0/files/FILE_ID
{ "shared_link": { "access": "open" } }
and then you'll get a response containing the created link:
{
...
"shared_link": {
"url": "https://www.box.com/s/rh935iit6ewrmw0unyul",
"download_url": "https://www.box.com/shared/static/rh935iit6ewrmw0unyul.jpeg",
"vanity_url": null,
"is_password_enabled": false,
"unshared_at": null,
"download_count": 0,
"preview_count": 0,
"access": "open",
"permissions": {
"can_download": true,
"can_preview": true
}
}
}

Related

how to access IndexedDB (of current opened domain/tab) from chrome extension

I currently have indexedDB on google.com domain. i want to be able to read it from google chrome extension. how can i accomplish this? do i need to add any specific permissions?
i currently have:
"permissions": [ "tabs", "bookmarks", "unlimitedStorage", "*://*/*", "identity", "https://*.google.com/*", "https://ssl.gstatic.com/", "https://www.googleapis.com/", "https://accounts.google.com/" ],
with what command i can do this? thank you!
Edit: i have readed i can access it from content script(aslong as the tab with domain is open - which is my case), but i dont know how to do that...
To access indexeddb of current tab add "activeTab" to "permissions" tag in manifest.json, Then create a content script, content script will be helpful in accessing the indexeddb as it runs in context of webpages, then add the content script created to the "content_scripts" tag in manifest.json file.
For Eg in manifest.json add the following:
"permissions": ["activeTab"],
"content_scripts": [
{
"matches": ["add the domains of the webpages where content script needs to run"],
"js": ["contentScript.js"]
}
]
For more info on matches check out here: https://developer.chrome.com/extensions/match_patterns
.
Inside content script add open the store and then perform transaction on the object store and perform queries on the object store.
For Eg in content script add following:
if (!('indexedDB' in window)) {
alert("This browser doesn't support IndexedDB");
} else {
let indexdb = window.indexedDB.open('firebaseLocalStorageDb', 1);
indexdb.onsuccess = function () {
let db = indexdb.result;
let transaction = db.transaction('firebaseLocalStorage', 'readwrite');
let storage = transaction.objectStore('firebaseLocalStorage');
console.log(storage.getAll());
};
}
Explanation of the above code:
It accesses the window object and opens the store "firebaseLocalStorageDb" with version "1", then after successfully accessing the object it looks for the result and performs transaction on the objectstore "firebaseLocalStorage" residing inside the store. Finally query the instance of objectstore "storage" to get all the key-value pairs.
For more info check: https://javascript.info/indexeddb
For anyone still interested, my solution to this problem -
this is placed in content script of extension -
chrome.extension.onConnect.addListener(function(port) {
if(port.name == "extension_request" ) {
port.onMessage.addListener(function(msg) {
if (msg.db) {
window.indexedDB.webkitGetDatabaseNames().onsuccess = function(sender,args)
{
var r = sender.target.result;
if(r.contains(msg.db)){
var openRequest = indexedDB.open(msg.db);
// your code
port.postMessage({foo: bar}); // your result which you want to send
}
}
}
}
}
and this is for background or popup script -
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
var port = chrome.tabs.connect(tabs[0].id,{name: "extension_request"});
port.postMessage({db: "database_name_example"}); // send database name
port.onMessage.addListener(function(msg) {
if (msg.foo ) {
// do your stuff in extension
}
}
}

Chrome Extension: How to change headers on every page request programmatically?

I'm currently developing a Chrome Extension and need to add/change a header value, but only on a specific page. Something like this:
chrome.onPageRequest(function(host) {
if(host == 'google.com') {
chrome.response.addHeader('X-Auth', 'abc123');
}
});
Any help would be greatly appreciated :)
You can use the chrome.webRequest API for that purpose. You'll need the following:
Declare the appropriate permissions in your manifest:
...
"permissions": [
...
"webRequest",
"*://*.google.com/*"
]
Register a listener for the chrome.webRequest.onHeadersReceived() event and modify the headers. In order to be able to modify the headers, you need to define the 'responseHeaders' extra info (see 3rd arguments of listener function):
chrome.webRequest.onHeadersReceived.addListener(function(details) {
console.log(details);
details.responseHeaders.push({
name: 'X-Auth',
value: 'abc123'
});
return { responseHeaders: details.responseHeaders };
}, {
urls: ['*://*.google.com/*']
}, [
"responseHeaders"
]);
Keep in mind that the webRequest permission only works if your background-page is persistent, so remove the corresponding line from your manifest (if it exists - which it should):
...
"background": {
"persistent": false, // <-- Remove this line or set it to `true`
"scripts": [...]
...
Also, keep in mind that pretty often Google redirects requests based on the user's country (e.g. redirecting www.google.com to www.google.gr), in which case the filter will not let them reach your onHeadersReceived listener.

Redirecting http to https using a Chrome extension

I am developing a number of Node.js applications that use an https server. While I am developing them, I run them on localhost using a self-signed certificate. Basically, everything works, but I have two issues:
When I point my browser to https://localhost:3000 for the first time, it warns me about a non-trusted certificate. This is, of course, true (and important), but it's annyoing while developing. Of course, I could add the certificate as a trusted one, but they change from time to time, and I don't want to clutter the certificate store.
Sometimes I just forget to enter the https part into the address bar, so Chrome tries to load the website using http. For whatever reason Chrome does not realize that there is no webserver responding to httprequests, instead it loads and loads and loads and …
What I would like to do to solve both issues is to create a Chrome extension that resides next to the address bar and offers a button with which you can toggle its state:
If the extension is disabled, it does nothing at all.
If the extension is enabled, and you send a request to localhost (and only then!), it shall do two things:
If the request uses http, but the page is still pending after a few seconds, it shall try using https instead.
Temporarily accept any certificate, no matter whether it's trusted by the browser or not.
To make it explicit: These rules shall only active for localhost.
So, now my questions are:
Is something like this possible using a Chrome extension at all?
As I have absolutely zero experience with writing Chrome extension, what would be a good starting point, and what terms should I look for on Google?
The Google Chrome Extensions Documentation is a great place to start. Everything you describe is possible using a Chrome Extension except for the "certificate accepting" part. (I am not saying it is not possible, I just don't know if it is - but I would be very surprised (and concerned) if it were.)
Of course, there is always the --ignore-certificate-errors command-line switch, but it will not differentiate between localhost and other domains.
If you decide to implement the rest of the functionality, I suggest looking into chrome.tabs and/or chrome.webRequest first. (Let me, also, mention "content scripts" are unlikely to be of any use.)
That said, below is some code for a demo extension (just to get you started).
What is does:
When deactivated -> nothing
When activated -> Listens for tabs being directed to URLs like http://localhost[:PORT][/...] and redirects them to https (it does not wait for a response or anything, it just redirects them instantly).
How to use:
Click the browser-action icon to activate/deactivate.
It's not perfect/complete, of course, but it's a starting point :)
Extension directory structure:
extention-root-directory/
|_____ manifest.json
|_____ background.js
|_____ img/
|_____ icon19.png
|_____ icon38.png
manifest.json:
(See here for more info on the possible fields.)
{
"manifest_version": 2,
"name": "Test Extension",
"version": "0.0",
"default_locale": "en",
"offline_enabled": true,
"incognito": "split",
// The background-page will listen for
// and handle various types of events
"background": {
"persistent": false, // <-- if you use chrome.webRequest, 'true' is required
"scripts": [
"background.js"
]
},
// Will place a button next to the address-bar
// Click to enable/disable the extension (see 'background.js')
"browser_action": {
"default_title": "Test Extension"
//"default_icon": {
// "19": "img/icon19.png",
// "38": "img/icon38.png"
//},
},
"permissions": [
"tabs", // <-- let me manipulating tab URLs
"http://localhost:*/*" // <-- let me manipulate tabs with such URLs
]
}
background.js:
(Related docs: background pages, event pages, browser actions, chrome.tabs API)
/* Configuration for the Badge to indicate "ENABLED" state */
var enabledBadgeSpec = {
text: " ON ",
color: [0, 255, 0, 255]
};
/* Configuration for the Badge to indicate "DISABLED" state */
var disabledBadgeSpec = {
text: "OFF",
color: [255, 0, 0, 100]
};
/* Return whether the extension is currently enabled or not */
function isEnabled() {
var active = localStorage.getItem("active");
return (active && (active == "true")) ? true : false;
}
/* Store the current state (enabled/disabled) of the extension
* (This is necessary because non-persistent background pages (event-pages)
* do not persist variable values in 'window') */
function storeEnabled(enabled) {
localStorage.setItem("active", (enabled) ? "true" : "false");
}
/* Set the state (enabled/disabled) of the extension */
function setState(enabled) {
var badgeSpec = (enabled) ? enabledBadgeSpec : disabledBadgeSpec;
var ba = chrome.browserAction;
ba.setBadgeText({ text: badgeSpec.text });
ba.setBadgeBackgroundColor({ color: badgeSpec.color });
storeEnabled(enabled);
if (enabled) {
chrome.tabs.onUpdated.addListener(localhostListener);
console.log("Activated... :)");
} else {
chrome.tabs.onUpdated.removeListener(localhostListener);
console.log("Deactivated... :(");
}
}
/* When the URL of a tab is updated, check if the domain is 'localhost'
* and redirect 'http' to 'https' */
var regex = /^http(:\/\/localhost(?::[0-9]+)?(?:\/.*)?)$/i;
function localhostListener(tabId, info, tab) {
if (info.url && regex.test(info.url)) {
var newURL = info.url.replace(regex, "https$1");
chrome.tabs.update(tabId, { url: newURL });
console.log("Tab " + tabId + " is being redirected to: " + newURL);
}
}
/* Listen for 'browserAction.onClicked' events and toggle the state */
chrome.browserAction.onClicked.addListener(function() {
setState(!isEnabled());
});
/* Initially setting the extension's state (upon load) */
setState(isEnabled());

Chrome extension run_at every post request it makes?

I have figured out how to run a script on every page load when it is done explicitly by user but I want to run my script each time it makes a post or get request in its back end on its own to the database or ad server implicitly. [For example on gmail if we keep our eyes on requests (maybe firebug - console - all) we will see that after certain time a POST request is getting fired from the browser on its own. ]
Is there any way I can do that?
Actually I am writing my first extension so it clearly states I don't know much about it.
You should use webRequest module in your extension. After specifing proper permissions in the manifest, for example:
"permissions": [
"webRequest",
"*://*/*"
],
"background": {
"scripts": ["background.js"]
},
you can register in your background page ("background.js" in the example) any required handlers, such as onBeforeRequest, onBeforeSendHeaders, onHeadersReceived, onCompleted, and others. I think the names are self-explaining, but you can consult with abovementioned documentation.
Depending from your requirements, you can define event handlers which prevent requests, modify headers, just read and somehow analyse http-headers.
Example for reading http headers and possibly changing them:
chrome.webRequest.onBeforeSendHeaders.addListener(
function(details)
{
console.log(details.url);
if(details.method == 'POST')
{
// do some stuff
for(var i = 0; i < details.requestHeaders.length; ++i)
{
// log or change some headers
// details.requestHeaders[i].name
// details.requestHeaders[i].value
}
}
return {requestHeaders: details.requestHeaders};
},
{urls: ["<all_urls>"]},
["blocking", "requestHeaders"]);

box api direct link for music file

dropbox has /media api that provides a direct link to be used for audio steaming with html5 audio tag. I do not see similar thing with box.
the real problem is that I cant use "GET /files/{file id}/content" for music streaming because it requires BoxAuth in header.
How do I do it?
Direct download link is only available for paid box users not for the free user. So if you are free user then you have to upgrade your account to paid user and then after you will get the direct download link. See the box support answer here
Or else you can use the download api. See the documentation
This link is only valid for 15 minutes so after 15 minutes you have to again call the download api and you will get the fresh direct download link valid for next 15 minutes.
When you create a shared link for the file, a direct download link is also returned i.e. the download_url field in the following JSON:
{
"type":"file",
"id":"2192049121",
"sequence_id":"1",
"name":"brand_new_name.psd",
"description":"",
"size":1266400,
"path":"\/brand_new_name.psd",
"path_id":"\/0\/2192049121",
"created_at":"2012-06-04T21:32:20-07:00",
"modified_at":"2012-06-04T21:32:21-07:00",
"shared_link": {
"url": "https://www.box.com/s/0bb6907e48920c98d484",
"download_url": "https://dl.boxcloud.com/shared/static/0bb6907e48920c98d484.webdoc",
"password_enabled": false,
"unshared_at": null,
"download_count": 0,
"preview_count": 0,
"access": "Open",
"permissions": {
"download": true,
"preview": true
}
}
"etag":"72e96dad26aa67a5f7435548c86b7a8a331f0ae9",
"created_by":
{
"type":"user",
"id":"13344957",
"name":"Sean Rose",
"login":"sean+test#box.com"
},
"modified_by":
{
"type":"user",
"id":"13344957",
"name":"Sean Rose",
"login":"seanrose#stanford.edu"
},
"owned_by":
{
"type":"user",
"id":"13344957",
"name":"Sean Rose",
"login":"seanrose#stanford.edu"
},
"parent":
{
"type":"folder",
"id":"0",
"sequence_id":null,
"name":"All Files"
}
}