getstream.io - feed retrieval responds with HTML instead of JSON - getstream-io

I am trying to retrieve a feed from getstream.io but it seems that the client is having trouble parsing the response because it is in HTML. Also not sure why the response says that the resource is not found, when the feed exists checking from the feed explorer on the getstream dashboard. I am currently using the stream-ruby gem.
(pry)> stream_client.feed('user', self.id).get
JSON::ParserError: lexical error: invalid char in json text.
<html> <head><title>302 Found<
(right here) ------^
I tried prying the stream-ruby gem and the error happens at stream-ruby-2.7.0/lib/stream/feed.rb upon the #client.make_request call
def get(params = {})
uri = "/feed/#{#feed_url}/"
if params[:mark_read] && params[:mark_read].is_a?(Array)
params[:mark_read] = params[:mark_read].join(',')
end
if params[:mark_seen] && params[:mark_seen].is_a?(Array)
params[:mark_seen] = params[:mark_seen].join(',')
end
auth_token = create_jwt_token('feed', 'read')
#client.make_request(:get, uri, auth_token, params)
end
This is how I initialise the client
#client ||= Stream::Client.new(
ENV['STREAM_API_KEY'],
ENV['STREAM_API_SECRET'],
location: ENV['STREAM_REGION']
)

Related

Revenuecat Webhook Issue

I have implemented webhook for revenuecat in .net core C#. But for some reason I am getting 400 badrequest with empty response. I am mostly sure that I am not getting the json response in webook through revenuecat for any of the event occurring.
I have also added endpoint on revenue cat webhook with authentication. I have tried several time and as I have not way to test this on local machine. I need help from revenue cat team to provide some reference doc with sample implementation just to get proper json response. Below is the code snippet that I am using to get json response from the webhook endpoint added in revenuecat.
var webHookSecret = _configuration[Constants.RevenueCatWebHookSecret]; var headerAuthorization = HttpContext.Request.Headers["Authorization"].ToString(); #region Check authorization if (webHookSecret == headerAuthorization) { json = await new StreamReader(HttpContext.Request.Body).ReadToEndAsync(); } else { _logger.Information($"Un-Authorized token access in revenuecat webhook. Returning BadRequest response."); throw new APIException(HttpStatusCode.Unauthorized, new APIError(_configuration, "InternalServerError")); }

INVALID_SIGNATURE error while trying to retrieve list of assemblies in transloadit

I am using Transloadit API to merge audio file and series of images.
At some point, I need to retrieve list of assemblies (videos generated till now) for which transloadit provides a get API endpoint but that endpoint accepts two query strings, signature and params(to configure the list)
I am generating signature of the same params which is being sent as query string to the API along with it's signature but it is returning an error that signature doesn't match.
Transloadit have proper docs of how to create signature for each major language here https://transloadit.com/docs/#signature-authentication
Also the docs (https://transloadit.com/docs/api/#assemblies-get) doesn't state whether the signature will be generated of the same params or not.
Please help if anyone have used transloadit and had a same problem before and solved it now
I believe what your problem may be is that you're not URL encoding the JSON before passing it in your GET request. Here's a small snippet in Python showing how to turn a dictionary of values into JSON to generate a signature, and then into a URL encoded object for the GET request.
params = {
'auth': {
'key': auth_key,
'expires': expires
},
'template_id': template_id
}
# Converts the dictionary into JSON
message = json.dumps(params, separators=(',', ':'))
signature = hmac.new(auth_secret.encode('utf-8'),
message.encode('utf-8'),
hashlib.sha1).hexdigest()
# URL encodes it
params_encoded = urllib.parse.quote_plus(message)
url = f'https://api2.transloadit.com/assemblies?signature={signature}&params={params_encoded}'
response = requests.get(url)

Unable to edit word document online using o365 MS Graph API getPreviewLinkWithEdit

Using o365 MS Graph API to edit word document online. https://learn.microsoft.com/en-us/graph/api/driveitem-preview?view=graph-rest-beta This feature was working till 22nd JAN 2021. We are not able to edit document online from 27th JAN.
Code:
public static String getPreviewLinkWithEdit(String itemId, InlineEditorConfig config, boolean editFlag) throws JSONException {
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.add(AUTHORIZATION, BEARER + config.getAccessToken());
String test = TEST;
if (!editFlag) {
test = TEST_WITHOUT_EDIT;
}
HttpEntity<String> request = new HttpEntity<>(test, headers);
ResponseEntity<String> response = restTemplate.exchange(HTTPS_GRAPH_BASE_URL_BETA + itemId + PREVIEW,
HttpMethod.POST, request, String.class);
return (null != response.getBody()
&& null != new JSONObject(response.getBody()).getString(GET_URL_STRING)
? new JSONObject(response.getBody()).getString(GET_URL_STRING)
: "");
}
Displaying the MS Word web URL in iframe:
<iframe id="imagepgframe" src="https://purushothamchowdary-my.sharepoint.com/personal/purushotham_purushothamch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NjktNDA4YS1hZTAzLTE2YjQ0OTdlMWQxNyIsInRpZCI6ImU2ZjI0ODVmLWE2ODMtNDM2ZS04ZmZhLTFkNzllZDIxZmFkMCIsImlwYWRkciI6IjE1Ny40MS4xNDIuMTQ2Iiwid29waV9hcCI6ImFsbGZpbGVzLndyaXRlIiwid29waV90dCI6IlByZUF1dGhUb2tlbiIsImFwcGN0eCI6IjI4OWU3YjdhZTVkMzQzZGM5NTdhNTU2NGNhOWZhZWI5O3ZYam1GZUVqbHNqeE0xWnkzMU9mRVZpSkFFMD07RGVmYXVsdDs7MTAyQjAzQzIzOTJFRjtUcnVlOzszYTg4ZjJlMy02ODY5LTQwOGEtYWUwMy0xNmI0NDk3ZTFkMTc7Njg7YjJmZWY4MTYtMTE4YS00N2I4LWFlMTItMTA2NzJhMDA2ZGRiIn0%2EOjcVqrRRrFrG6YNacnl2h32Hd1exc30YMGhrTdhJ2nSxhciaYqrMWkhLUMz7hDxyONMtgHVUzBty%2DNP2WUtDibf%2DKzOCTTW9aF01ytp%5FQTqIikpdDLUkyXQwDuJQzKuZh8vjxSXF5jfYtoK7JyqUNXZfllozebrqXe80arK%2DTNvvqAk3tOqF5yBedEYW0KrIIyFlyPNXNMyxdGBNEvRjMpMBqzE0Pn3wBiWeh6q4Bx8qSCYE9HwObPDUNtw%2DtCZh%2DFx6suS%5F3kuntWjyxKOqYRfYWpt%5FrWwFCxbFvWwThG5JcT1RUWHi0vdvA9%2DVGn%5FMUqxuKr9BQjUaQC9SFIhaMw"></iframe>
The word document file is getting uploaded to OneDrive. In application getting the web URL to open the word document in browser. The application java code works fine without giving any error .
Preview Link :
https://graph.microsoft.com/beta/me/drive/items/01ZPAXLBD2POPCRU7F3RBZK6SVMTFJ7LVZ/preview
In iframe bellow error getting displayed:
Error in browser console:
Failed to execute 'postMessage' on 'DOMWindow': The target origin provided ('https://word-edit.officeapps.live.com') does not match the recipient window's origin ('https://sheethaljav-my.sharepoint.com').
Cookie:
Upon your description, there's no error message in your java code, so maybe you can debug your code to get the real 'GET_URL_STRING' to check if it has got the correct link url.
And I have test the api in api test tool, with ropc flow to get an access token and then calling 'https://graph.microsoft.com/beta/me/drive/items/【itemid】/preview'(according to your code, I assumed you're using this one) and I got the error of 'notAllowed', then I delete the suffix '/preview' and it replied with the url. So could you pls add more details on your debug result?

Azure Text to Speech started returning "400 Bad Request" all the sudden

I was using Azure Text-to-Speech API succesfully for months with this format:
<speak version='1.0' xmlns='w3.org/2001/10/synthesis' xml:lang='en-US'><voice name='Microsoft Server Speech Text to Speech Voice (fi-FI, HeidiRUS)'>My text</voice></speak>
But suddenly this request started returning:
HTTP/1.1 400 Bad request
We were using the same request successfully for months (with different phrase of course) but just some weeks ago the same request started returning this error. I don't get any additional information so I don't know where to look. Azure documentation says:
A required parameter is missing, empty, or null. Or, the value passed
to either a required or optional parameter is invalid. A common issue
is a header that is too long.
I also tried making the request more specific by adding gender and language and replacing single quotes with double quotes, but no use:
<speak version="1.0" xmlns="w3.org/2001/10/synthesis" xml:lang="fi-FI" xml:gender="Female"><voice name="Microsoft Server Speech Text to Speech Voice (fi-FI, HeidiRUS)">Text.</voice></speak>
Did something change in the API? Or what is missing in my request?
I got a 200 OK with the right content when I send the following payload:
<speak version='1.0' xmlns='http://www.w3.org/2001/10/synthesis' xml:lang='en-US'><voice name='Microsoft Server Speech Text to Speech Voice (fi-FI, HeidiRUS)'>This is my test</voice></speak>
Here is my C# code to send this:
// Generate request
string body = $#"<speak version='1.0' xmlns='http://www.w3.org/2001/10/synthesis' xml:lang='{voiceLang}'><voice name='{voiceName}'>{text}</voice></speak>";
using (var client = new HttpClient())
{
using (var request = new HttpRequestMessage())
{
// Set the HTTP method
request.Method = HttpMethod.Post;
// Construct the URI
request.RequestUri = new Uri(ttsHostUri);
// Set the content type header
request.Content = new StringContent(body, Encoding.UTF8, "application/ssml+xml");
// Set additional header, such as Authorization and User-Agent
request.Headers.Add("Authorization", "Bearer " + accessToken);
request.Headers.Add("Connection", "Keep-Alive");
// Update your resource name
request.Headers.Add("User-Agent", "YOUR_RESOURCE_NAME");
request.Headers.Add("X-Microsoft-OutputFormat", "riff-24khz-16bit-mono-pcm");
// Create a request
using (var response = await client.SendAsync(request).ConfigureAwait(false))
{
response.EnsureSuccessStatusCode();
// Asynchronously read the response
using (var dataStream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false))
{
// ... Process your audio here
}
}
}
}
The only difference that I can see on our payloads is the xmlns value where I have a full url (with http://) whereas yours doesn't get it.
The error may be elsewhere: are you sure you are authenticating yourself when querying the endpoint?
We also suddenly got the 400 error and in our case we had missed to encapsulate the text for the XML request with
<![CDATA[ your text here ]]>
after we did that in our code we got no more reported 400 errors by the users.

How do I escape a '/' in the URI for a GET request?

I'm trying to use Groovy to script a GET request to our GitLab server to retrieve a file. The API URI format is:
https://githost/api/v4/projects/<namespace>%2F<repo>/files/<path>?ref=<branch>
Note that there is an encoded '/' between namespace and repo. The final URI needs to look like the following to work properly:
https://githost/api/v4/projects/mynamespace%2Fmyrepo/files/myfile.json?ref=master
I have the following code:
File f = HttpBuilder.configure {
request.uri.scheme = scheme
request.uri.host = host
request.uri.path = "/api/v4/projects/${apiNamespace}%2F${apiRepoName}/repository/files/${path}/myfile.json"
request.uri.query.put("ref", "master")
request.contentType = 'application/json'
request.accept = 'application/json'
request.headers['PRIVATE-TOKEN'] = apiToken
ignoreSslIssues execution
}.get {
Download.toFile(delegate as HttpConfig, new File("${dest}/myfile.json"))
}
However, the %2F is re-encoded as %252F. I've tried multiple ways to try and create the URI so that it doesn't encode the %2F in between the namespace and repo, but I can't get anything to work. It either re-encodes the '%' or decodes it to the literal "/".
How do I do this using Groovy + http-builder-ng to set the URI in a way that will preserve the encoded "/"? I've searched but can't find any examples that have worked.
Thanks!
As of the 1.0.0 release you can handle requests with encoded characters in the URI. An example would be:
def result = HttpBuilder.configure {
request.raw = "http://localhost:8080/projects/myteam%2Fmyrepo/myfile.json"
}.get()
Notice, the use of raw rather than uri in the example. Using this approach requires you to do any other encoding/decoding of the Uri yourself.
Possible Workaround
The Gitlab API allows you to query via project id or project name. Look up the project id first, then query the project.
Lookup the project id first. See https://docs.gitlab.com/ee/api/projects.html#list-all-projects
def projects = // GET /projects
def project = projects.find { it['path_with_namespace'] == 'diaspora/diaspora-client' }
Fetch Project by :id, See https://docs.gitlab.com/ee/api/projects.html#get-single-project
GET /projects/${project.id}

Resources