according to the Google Drive SDK Update sharing permissions and https://developers.google.com/drive/v2/reference/permissions I want to change the whole folder content to be available for viewing (the folder contains only images and I show them on my page with <img alt='' src='https://drive.google.com/uc?export=view&id="fileID"'/>)
so, I'm trying to use that code
PermissionList permissions = Google_DriveService.Permissions.List(fileId).Fetch();
var filePermissions = permissions.Items;
Permission permission = Google_DriveService.Permissions.Get(fileId, filePermissions[0].Id).Fetch();
permission.Role = "reader";
permission.Value = "me";
permission.Type = "anyone";
permission.WithLink = true;
var updated = Google_DriveService.Permissions.Update(permission, fileId, filePermissions[0].Id).Fetch();
but I get the error message
Google.Apis.Requests.RequestError Invalid permission type specified [400] Errors [ Message[Invalid permission type specified] Location[ - ] Reason[invalid] Domain[global] ]
what am I doing wrong ?
Tony's answer is correct and here is an addon to his instruction if anyone else is looking to test this. Note that I did not write up the code for this due to time constraints but I tested it using the Google API supplied on the Google Drive web api page. I tested this by doing the following:
Go to the following link and list all the files in your drive. https://developers.google.com/drive/v2/reference/files/list
Select one file that you want to share for read only access and copy out the "id" as per the screenshot below:
Go to the insert permission page here - Tony was correct, you do not delete the existing permission but instead, you add onto that permission: https://developers.google.com/drive/v2/reference/permissions/insert
In the API explorer, type in "role" as "reader" and "type" as "anyone".
Go to your Drive: https://drive.google.com/drive/#my-drive and you will see that the file is now shared - if you hover over the green link icon in the screenshot below, it will tell you that it is now shared.
You can also copy the link for the doc and paste it into Incognito mode in Chrome to test whether you can access the read-only version of the doc in Incognito mode and it should work.
Additional:
The code should not be too hard, here it is:
Permission newPermission = new Permission();
newPermission.setType("anyone");
newPermission.setRole("reader");
try {
return service.permissions().insert(fileId, newPermission).execute();
} catch (IOException e) {
System.out.println("An error occurred: " + e);
}
You can't change permission types with update requests, insert a new permission and delete the existing. You should also not use me as a principal related to an anyone permission. Anyone permissions dont expect value attributes to be set.
This is the new reference of the API: https://developers.google.com/drive/v3/reference/permissions/create
Related
I am trying to figure how to get or create a hyperlink in only part of a Google Spreadsheets cell. For example, if my cell was written in markdown, it would look like this:
Device ID, found on [the inventory website](https://www.example.com/)
I tried the methods CellFormat#getHyperlinkDisplayType() and CellData#getHyperlink(), both of which returned null. I examined all the cell data in my debugger, and did not see the URL present anywhere. This gives me reason to believe that I need include another field in the setFields method:
Sheets sheets = auth.getService();
Get request = sheets.spreadsheets().get(id).setFields(
"sheets.properties,sheets.data.rowData.values(effectiveValue,effectiveFormat.backgroundColor)");
Spreadsheet response = request.execute();
I am not sure which field would include the hyperlink, nor can I find a list of the fields available to me. I was also wishing to be able to create a hyperlink which only covers part of the text in a cell.
Is this possible?
I believe your goal as follows.
You want to retrieve or create a hyperlink in a part of text in a cell using Sheets API.
As a sample situation, you want to retrieve https://www.example.com/ from the cell "B1" of the following situation of Spreadsheet. And also, you want to create the situation like the cell "B1".
Row
Column A
Column B
1
Device ID
found on the inventory website
Issue and workaround:
Unfortunately, in the current stage, there are not methods for retrieving and creating a hyperlink in a part of text in a cell using Sheets API. So in this answer, I would like to propose a workaround to achieve your goal.
In this workaround, the Web Apps created by Google Apps Script is used as the wrapper. Because when Spreadsheet service of Google Apps Script is used, your goal can be directly achieved. Ref The Web Apps is used like an API. So the flow of this workaround is as follows.
At client side, request to the Web Apps.
At Web Apps side, retrieve and create the hyperlink in a part of text in a cell using Google Apps Script.
Return the result to the client side.
In order to use this workaround, please do the following flow.
Usage:
1. Create new project of Google Apps Script.
Sample script of Web Apps is a Google Apps Script. So please create a project of Google Apps Script.
If you want to directly create it, please access to https://script.new/. In this case, if you are not logged in Google, the log in screen is opened. So please log in to Google. By this, the script editor of Google Apps Script is opened.
2. Prepare Web Apps side. (server side)
Please copy and paste the following script (Google Apps Script) to the script editor and save the project. This script is for the Web Apps. This Web Apps is used as an API.
// This function is used for retrieving the hyperlinks from a sheet in a Google Spreadsheet.
function doGet(e) {
let returnValue = "";
const {method, spreadsheetId, sheetName} = e.parameter;
if (method == "get") {
const res = getHyperlinks(spreadsheetId, sheetName);
returnValue = JSON.stringify(res);
} else {
returnValue = "Error: No method.";
}
return ContentService.createTextOutput(returnValue);
}
// This function is used for creating a cell including the hyperlinks in a part of cell text on a sheet in a Google Spreadsheet.
function doPost(e) {
let returnValue = "";
const {method, spreadsheetId, sheetName} = e.parameter;
if (method == "create") {
if (e.postData) {
const res = createHypetlinks(spreadsheetId, sheetName, JSON.parse(e.postData.contents));
returnValue = JSON.stringify(res);
} else {
returnValue = "Error: No object for creating hyperlink in a cell.";
}
} else {
returnValue = "Error: No method.";
}
return ContentService.createTextOutput(returnValue);
}
function createHypetlinks(spreadsheetId, sheetName, object) {
const ss = SpreadsheetApp.openById(spreadsheetId);
const sheet = ss.getSheetByName(sheetName);
const range = sheet.getRange(object.rowIndex + 1, object.columnIndex + 1);
const builder = SpreadsheetApp.newRichTextValue().setText(object.cellText);
object.hyperlinks.forEach(({startIndex, endIndex, url}) => builder.setLinkUrl(startIndex, endIndex, url));
range.setRichTextValue(builder.build());
return "Done.";
}
function getHyperlinks(spreadsheetId, sheetName) {
const ss = SpreadsheetApp.openById(spreadsheetId);
const sheet = ss.getSheetByName(sheetName);
const richTextValues = sheet.getDataRange().getRichTextValues();
const hyperlinks = richTextValues.reduce((ar, r, i) => {
r.forEach((c, j) => {
const temp = c.getRuns().reduce((arr, r) => {
const link = r.getLinkUrl();
if (link) {
arr.push({text: r.getText(), hyperlink: link});
}
return arr;
}, []);
if (temp.length > 0) {
ar.push({rowIndex: i, columnIndex: j, hyperlinks: temp});
}
});
return ar;
}, []);
return hyperlinks;
}
3. Deploy Web Apps.
The detail information can be seen at the official document.
On the script editor, at the top right of the script editor, please click "click Deploy" -> "New deployment".
Please click "Select type" -> "Web App".
Please input the information about the Web App in the fields under "Deployment configuration".
Please select "Me" for "Execute as".
This is the important of this workaround.
Please select "Anyone" for "Who has access".
In this case, the user is not required to use the access token. So please use this as a test case.
When you want to use the access token, please set it to Anyone with Google account or Only myself. By this, the user can access to the Web Apps using the access token. When you use the access token, please include the scope of https://www.googleapis.com/auth/drive.readonly or https://www.googleapis.com/auth/drive.
Please click "Deploy" button.
When "The Web App requires you to authorize access to your data" is shown, please click "Authorize access".
Automatically open a dialog box of "Authorization required".
Select own account.
Click "Advanced" at "This app isn't verified".
Click "Go to ### project name ###(unsafe)"
Click "Allow" button.
Copy the URL of Web App. It's like https://script.google.com/macros/s/###/exec.
When you modified the Google Apps Script, please redeploy as new version. By this, the modified script is reflected to Web Apps. Please be careful this.
3. Testing.
As a simple test, when it requests to the Web Apps using a curl command, it becomes as follows. Please set your Web Apps URL, the method, spreadsheet ID and sheet name, and also, the request body. When the Web Apps is correctly deployed, the values are returned.
Retrieve hyperlinks from a sheet.
$ curl -L 'https://script.google.com/macros/s/###/exec?method=get&spreadsheetId={your Spreadsheet ID}&sheetName=Sheet1'
The start index of rowIndex and columnIndex is 0. So for example, rowIndex: 1 and columnIndex: 1 is the cell "B2";
When your Web Apps is correctly deployed and your curl command is correct and the spreadsheet has the sample of top table, the following result is obtained.
[
{
"rowIndex":0,
"columnIndex":1,
"hyperlinks":[{"text":"the inventory website","hyperlink":"https://www.example.com/"}]
}
]
Create a cell including hyperlinks.
$ curl -L -d '{"rowIndex": 0, "columnIndex": 2, "cellText": "found on the inventory website", "hyperlinks": [{"startIndex": 9, "endIndex": 30, "url": "https://www.example.com/"}]}' 'https://script.google.com/macros/s/###/exec?method=create&spreadsheetId={your Spreadsheet ID}&sheetName=Sheet1'
The start index of startIndex and endIndex is 0. So for example, when the cell text is sample text and you want to give the link to text, startIndex and endIndex is 7 and 11, respectively;
When above sample curl command is run, found on the inventory website is put to the cell "C1" and the inventory website has the hyperlink of https://www.example.com/ as follows. And, you can see Done. at the console.
Note:
When you modified the script of Web Apps, please redeploy the Web Apps as new version. By this, the latest script is reflected to Web Apps. Please be careful this.
References:
Web Apps
Taking advantage of Web Apps with Google Apps Script
Class RichTextValueBuilder
Related thread
How to extract the link from a cell now that links are not reflected as HYPERLINK?
I am trying to get the modified content after the given time from google sheets. Nowhere I can found the api to get the data. What i can see is getting modified date alone from the drive Api. How can I get the data using Drive or Sheets Api? Give me the suggestions if Possible
Google Drive keeps a track of revision history of files that are contained on it. There is however, no way to obtain the revisions from a request alone.
Google allows for you to receive email notifications whenever a user makes an edit to your sheet, which you can set up by completing the following steps:
In the Spreadsheet's web view, click Tools -> Notification rules...
Under Notify me at myemail#address.ext when... select Any changes are made
Under Notify me with... select Email - right away
Click Save.
You should also be aware that you will not get a notification for edits made to the sheet by you - notifications are only received when another user edits the sheet. Whenever you get an email notification, you will receive a link to view the changes to the spreadsheet in the form of a read-only web view link.
You can work around this programatically, though there isn't one right way and it can be quite complicated. You can use the Revisions: list method of the Drive REST API to get the information about the user that made an edit, as well as a list of links which you can use to export that revision of the sheet to another MIME Type, as shown below in the request response.
Requesting:
GET https://www.googleapis.com/drive/v3/files/SPREADSHEET_ID/revisions
with revisions/exportLinks,revisions/lastModifyingUser/emailAddress as the fields field and replacing SPREADSHEET_ID with the ID of the spreadsheet will give you a 200 response:
{
"revisions": [
{
"lastModifyingUser": {
"emailAddress": "username#domain.ext"
},
"exportLinks": {
"application/x-vnd.oasis.opendocument.spreadsheet": "https://docs.google.com/spreadsheets/export?id=SPREADSHEET_ID&revision=revisionNumber&exportFormat=ods",
"text/tab-separated-values": "https://docs.google.com/spreadsheets/export?id=SPREADSHEET_ID&revision=revisionNumber&exportFormat=tsv",
"application/pdf": "https://docs.google.com/spreadsheets/export?id=SPREADSHEET_ID&revision=revisionNumber&exportFormat=pdf",
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": "https://docs.google.com/spreadsheets/export?id=SPREADSHEET_ID&revision=revisionNumber&exportFormat=xlsx",
"text/csv": "https://docs.google.com/spreadsheets/export?id=SPREADSHEET_ID&revision=revisionNumber&exportFormat=csv",
"application/zip": "https://docs.google.com/spreadsheets/export?id=SPREADSHEET_ID&revision=revisionNumber&exportFormat=zip",
"application/vnd.oasis.opendocument.spreadsheet": "https://docs.google.com/spreadsheets/export?id=SPREADSHEET_ID&revision=1&exportFormat=ods"
}
}
]
}
With the links to individual changes, you can fetch and compare the different versions of the Sheet using Apps Script, and output A1 notation of the cells that have different values between versions. This, with the email address from the original Revisions: list request, is enough to compile a file or a log containing.
You can put this into a simple onEdit() trigger bound to the sheet will allow you to automatically get the changes each time a user edits the sheet.
This picture is of the upload fragment made by me using android studio and when the list item is been clicked the object should be downloaded.It's Working fine and the object is been downloaded on my phone and the other phone on which I installed it. But when I shared this application to others it gives the error marked in the picture on their phones.Updating the play services is not removing the error.
After 2 days of frustration, I found out that there is a bug in firebase storage.Thus, you've to simply turn off and on your storage manually,thanks.
May be this is the wrong path bug but in my case resolve this here is the example
i use this code then i received error
public static StorageReference getChildProfileStorage(String vid){
StorageReference storageReference= FirebaseStorage.getInstance().getReference();
storageReference.child("ParentDataStore").child(CurrentUser.getInstance().getEmail())
.child("ChildDataStore").child(vid);
return storageReference;
}
here is the line that solve my problem
public static StorageReference getStudentProfileStorage(String vid){
StorageReference storageReference= FirebaseStorage.getInstance().getReference("ParentDataStore")
.child("StudentDataStore").child(vid).child("profile");
return storageReference;
}
Sorry, I am late. but today I am also facing the same issue. What I've done is to update the storage library in build.Gradle (app) file. and it solved my problem.
Basically when you configure storage using Android studio firebase assistant. This will import the older version of the app. So don't to update a newer version
For me, I was providing invalid system file path while calling getFile() of the FileDownloadTask, I was initially trying to download a file from Firebase.
Here the issued is raised as the downloadDirectory was invalid
File localFile = ...;
FileDownloadTask downloadTask = FirebaseStorage.getInstance()
.getReference()
.child("fileName")
.getFile(localFile);
Here the path of the localFile I was providing was invalid.
After 3-4 hrs depression,i got the actual reason.
While downloading,I need to give storage permission of writing but I only gave read permission. In lower androids , read-write permission is same.Basically I was used to/accustomed to these lower version devices that's why forget to add write storage permission for the upper androids
I had the same issue and when I checked the Storage rules:
allow read, write: if false
I saw it was.
It worked when I changed it to:
allow read, write: if true
I've just updated the implementation in the build.gradle(:app) to
implementation 'com.google.firebase:firebase-storage:20.0.1'
On microsoft graph explorer i am able to retrieve the excel file easily but when trying on the "active-directory-android-native-v2-master" sample code, it returns 404.
On the the other hand, next line works and retrieves my information correctly
final static String MSGRAPH_URL = "https://graph.microsoft.com/v1.0/me";
I added all required permissions, got the client ID, run all the sample instructions, read the documentation + stack over flow.
I thought it might be because the link was not coded correctly so i modified the callGraphAPI() method to include:
Uri.Builder builder = new Uri.Builder();
builder.
scheme("https").
authority("graph.microsoft.com").
appendPath("v1.0").
appendPath("drives").
appendPath(MY_DRIVE).
appendPath("items").
appendPath(FILE_ID).
appendPath("workbook");
String url = builder.build().toString();
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET,url/*MSGRAPH_URL*/,
parameters,new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
but still the same response.
I came across the next stack overflow answer
404 file not found error when using microsoft graph api
And thought it might be the answer but then seen the question was old and another answer mentioned it is not longer correct.
appreciate any help.
It seems i was not aware using sample code for the V2 (active-directory-android-native-v2-master) while the graph explorer (which was working) used V1.
There is a great "getting started" tutorial for the V1 sample code (active-directory-android-master) here:
https://learn.microsoft.com/en-us/azure/active-directory/develop/quickstart-v1-android
Sample code seems quite the same only for V1.
When using the tutorial, i needed to find the required permissions for the command i was trying to use, in addition to the one mentioned at the tutorial.
I used the next link to get the permissions for the items:
https://developer.microsoft.com/en-us/graph/docs/api-reference/v1.0/api/shares_get
I also added the permissions mentioned at the Graph Exlorer since as noted, the command i was trying to use worked there.
Since the permissions at the Azure site was not written the same (e.g. Files.Read is written as "Read user files") i used the next link to translate:
https://developer.microsoft.com/en-us/graph/docs/concepts/permissions_reference
Luckily i did not need to use any admin permissions, which would have complicated the registration to the app
Hopes this helps any struggled newbie like me :)
If anything from what i wrote not correct or you think i should add something, please let me know at the comments below and i will try to update
BTW - i used the Graph Exlorer to detect the files & Drive ID items i needed
I'm attempting to send an image to Hangouts from within an app I'm building.
I'm working in Xamarin for VS 2015 to do this so the code below is c# but it's not much different from the equivalent Java code so I think it's easy to follow.
What I've done is set up a button on my app which has code setting up an Intent to share an image to Hangouts. I've set the image up already in the Downloads folder on the device and hardcoded the name into the code.
Intent hangoutsShareIntent = new Intent(Intent.ActionSend);
hangoutsShareIntent.SetType("image/jpeg");
hangoutsShareIntent.SetPackage("com.google.android.talk");
string downloadsPath = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDownloads).AbsolutePath;
string filePath = Path.Combine(downloadsPath, "shared.jpg");
hangoutsShareIntent.PutExtra(Intent.ExtraStream, filePath);
StartActivity(Intent.CreateChooser(hangoutsShareIntent, "Share with"));
When I run this, I get the option to select a chat in Hangouts that I want to send the content to. Upon selecting the chat, I get a blank message box and no image.
I've swapped the above code over to use text/plain and pass the filePath variable to the message. When I copy the file path into Chrome to check it, the image loads so I have to figure that the image is where I've said it is... right?
I get no errors (probably because the issue is in Hangouts rather than my app so I have nothing to debug there). Logcat shows nothing except an error I can't find much about on Google: ExternalAccountType﹕ Unsupported attribute readOnly
The only information I could find on that error implied some issue with permissions but I've made sure my app has runtime permissions checked for Read/Write using this code (which wraps the above):
if ((CheckSelfPermission(Permission.ReadExternalStorage) == (int)Permission.Granted) &&
(CheckSelfPermission(Permission.WriteExternalStorage) == (int)Permission.Granted))
NOTE: I'm running this on a HTC One M8 - no SD card but does have external storage on device. I've also added the above permissions to the manifest for earlier Android versions.
The documentation for this (here) isn't overly helpful either so any advice AT ALL here is welcome :)
Thanks!
If you use the file provider instead of sending just the URI on its own. This should get around the permission issues you are seeing.
There is a guide available here which might be useful.
Intent shareIntent = new Intent(Intent.ActionSend);
shareIntent.SetType("image/gif");
Java.IO.File file = new Java.IO.File(Android.OS.Environment.ExternalStorageDirectory + "/myimage.gif");
Android.Net.Uri fileUri = Android.Support.V4.Content.FileProvider.GetUriForFile(this, "com.myfileprovider", file);
shareIntent.SetPackage("com.google.android.talk");
shareIntent.AddFlags(ActivityFlags.GrantReadUriPermission);
shareIntent.PutExtra(Intent.ExtraStream, fileUri);
StartActivity(Intent.CreateChooser(shareIntent, "Share with"));