how to create a new page and upload a text file into the confluence space - confluence

i have a script that gets a text file as an output, i want this text file to be uploaded in the confluence space but i am not sure how to do it.
this is a sample script that i found off the internet but this is not working for me
import urllib2
import base64
conf_serverurl = "https://confluence.mycompany.com/"
username = "myusername"
password = "mypassword"
stringToEncode = username + ":" + password
encodedString = base64.b64encode(stringToEncode)
url = conf_serverurl + "/rest/api/content?os_username=" + username + "&os_password=" + password
data = '{"type":"page","ancestors":[{"type":"page","id":18166401}],"title":"new page","space":{"key":"ds"},"body":{"storage":{"value":"<p>This is a new page</p>","representation":"storage"}}}'
headers = { 'Authentication': 'Basic ' + encodedString, 'Content-type': 'application/json', 'Accept': 'application/json', 'X-Atlassian-Token': 'no-check' }
req = urllib2.Request(url, data, headers=headers)
try:
response = urllib2.urlopen(req)
data = response.read()
except urllib2.HTTPError, error:
data = error.read()
print data
but this code is throwing me the error
{"message":"null for uri: https://confluence.mycompany.com//rest/api/content?os_username=ppanda&os_password=mypassword","status-code":404}
what can be wrong here??
credentials??/ code??

First thing that comes to my mind that you do have double "/" in your URL. Because in conf_serverurl you do have "https://confluence.mycompany.com/" and in your URL you will add /rest/api/... So, I would say remove one of the / from your code and check.
Also, please take a look at Atlassian Documentation for finding proper REST endpoint of creating page and uploading attachments.

Related

Failed to upload apk via Connect API

I am working on a python script to update the app on Huawei AppGallery via Connect API.
I successfully fetched the token and upload URL but not able to upload the APK/AAB.
Getting this error -
{'result': {'CException': {'errorCode': 70001405, 'errorDesc': 'get no file from request!'}, 'resultCode': '70001405'}}
Here's my python script
def uploadAAB(uploadUrl, authCode, accessToken, appId):
try:
fileName = 'latest_hms.apk'
headers = {
"Authorization": "Bearer " + accessToken,
"accept": "application/json",
"client_id": clientId,
"Content-Type": "multipart/form-data"
}
uploadBody = {
"authCode": authCode,
"fileCount": 1
}
with open(aabPath, 'rb') as f:
f.seek(0, os.SEEK_END)
print(f.tell()) # printing the correct size
first_phase = requests.post(
uploadUrl,
files={fileName: f},
data=uploadBody,
headers=headers)
if first_phase.status_code == 200:
print(first_phase.json())
body = {
'fileType': 5,
'files': [{
'fileName': fileName,
'fileDestUrl': first_phase.json()['result']['UploadFileRsp']['fileInfoList'][0]['fileDestUlr'],
'size': str(first_phase.json()['result']['UploadFileRsp']['fileInfoList'][0]['size'])
}]
}
fileHeader = {
'client_id': clientId,
'Authorization': 'Bearer ' + accessToken,
}
params = {
'appId': appId,
}
second_phase = requests.put(
BASE_URL + "/publish/v2/app-file-info",
headers=fileHeader,
json=body,
params=params)
print(second_phase.json())
except (requests.exceptions.RequestException, requests.exceptions.HTTPError, KeyError) as err:
stopOnError(repr(err))
Please help me out here.
{'result': {'CException': {'errorCode': 70001405, 'errorDesc': 'get no file from request!'}, 'resultCode': '70001405'}}
This error means there is no file in the request. the file is not include successfully in the request. Please make sure the file is achievable.
It seems Huawei made a change to the AppGallery API in February 2022. I don't know if this was intentional, but you must now specify a filename of "file" instead of your original filename (which worked before). See my pull request on Natgho's HMS-Publishing-API code.

How to convert this curl example to google apps script / javascript? [duplicate]

I have experience making CURL calls in GAS using headers and payload, but I have never done a CURL command using the -u option before. According to the API spec, I must use the -u option. I just don't know how to convert that to GAS. Here is my code so far:
function updateStatus()
{
//Build header.
var header =
{
'Content-Type': 'application/json', //Set content type to JSON.
};
//Put it all together.
var options =
{
'method' : 'get',
'headers' : header
};
//Make Login call to When I work.
var responseGetPlan = UrlFetchApp.fetch('my url', options);
var strResponseGetPlan = responseGetPlan.getContentText();
Logger.log('Get Plan Response: ' + strResponseGetPlan); //Log response.
var parsedData = JSON.parse(strResponseGetPlan); //Parse into JSON format.
var strId = parsedData.id;
Logger.log(strId);
}
curl -u uses Basic authentication, which is a simple base64 encoding of a concatenated "username:password" string. You would send the following as headers.
Authorization: 'Basic ' + Utilities.base64Encode('username:password')
References:
RFC7617
curl Basic Authentication
Utilities

Error while generating access_token using Ebay 's REST API - Python requests

I'm trying to use the ebay REST-API for the first. I am simply trying to generate an access_token using the client credentials grant-request. I followed the instructions here https://developer.ebay.com/api-docs/static/oauth-client-credentials-grant.html
HTTP method: POST
URL (Sandbox): https://api.sandbox.ebay.com/identity/v1/oauth2/token
HTTP headers:
Content-Type = application/x-www-form-urlencoded
Authorization = Basic <B64-encoded_oauth_credentials>
Request body (wrapped for readability):
grant_type=client_credentials&
redirect_uri=<RuName-value>&
scope=https://api.ebay.com/oauth/api_scope
I'm getting this error: {'error': 'invalid_client', 'error_description': 'client authentication failed'} and my code looks like this:
path = 'https://api.sandbox.ebay.com/'
app_json = 'application/json'
headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': base64.b64encode(b'Basic CLIENT_ID:CLIENT_SECRET')
}
payload = 'grant_type=client_credentials&redirect_uri=Searchez&scope=https://api.ebay.com/oauth/api_scope'
def get_oath_token():
url = 'https://api.sandbox.ebay.com/identity/v1/oauth2/token'
r = requests.post(url, headers=headers, data=payload)
print(r.json())
get_oath_token()
What do I have configured incorrectly? Thanks.
You're base64encoding "Basic " and shouldn't be.
The doc says just encode your Client ID + ":" + Client Secret, and leave the word "Basic" and the space that follows it alone.
In your code, i can see sandbox endpoint URI but in the request body scope, you have used production URL, instead of sandbox

ionic 3 header not sending Authorizaqtion 'bearer "token"' to server

Im doing a login screen that takes a username and password.
if the login was successful the server will return a token.
then im trying to call another function to get user info but the authorization header is not being passed.
im trying my server method on postman and its working fine so i believe the problem is in the headers. May someone please advise me on what should be done?
let url = urlConst.Login;
let params1 = new HttpParams();
let loader = this.loadingcontroller.create({
content: stringEngConst.signinngin
});
let attributes = {
username: this.uname.value.toLowerCase(),
password: this.password.value,
grant_type: "password"
};
var headers = new HttpHeaders();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
let body = 'username=' + this.uname.value.toLowerCase() + '&password=' + this.password.value + '&grant_type=password';
let data: Observable < any > = this.http.post(url, body, {
headers: headers
});
loader.present().then(() => {
data.subscribe(result => {
if (result.access_token != null) {
this.signintoken = result.access_token;
this.storage.set(storageConst.SIGN_IN_TOKEN, result.token_type + " " + result.access_token);
headers.append('Authorization', 'Bearer ' + this.signintoken);
let url1 = 'http://localhost:57940/API/Account/GetUserInfo/';
let info: Observable < any > = this.http.get(url1, {
headers: headers
});
info.subscribe(result => {
/*Do Something*/
});
}
Please Note that result.access_token != null is true. and i am successfully getting the token back. But it is not being passed again to the second url (info)
Looks like this SO post may solve things for you: https://stackoverflow.com/a/47805759/6599076
You may want to use:
headers = headers.append('Authorization', 'Bearer ' + this.signintoken);
You are using the same headers as for the first http request:
var headers = new HttpHeaders();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
Depending on your end point for the subsequent call it might be that you need to set headers differently:
Try creating new headers with
var headers2 = new HttpHeaders();
headers.append('Content-Type', 'application/json');
Or get rid of Content-Type completely depending on what your end point expects.
Also if you are using Ionic 3 its worth to check which Http module you are using (HttpClient or the older one) as there are some differences in how these tend to handle request options.

Google Apps Script - create draft Gmail email message WITH embedded graphics

I want to create a draft Gmail email message using Google Apps Script, like in the following example taken from Mogsdad's accepted answer to the Create draft mail using Google apps script question:
function createDraft() {
var forScope = GmailApp.getInboxUnreadCount(); // needed for auth scope
var raw =
'Subject: testing Draft\n' +
//'To: test#test.com\n' +
'Content-Type: multipart/alternative; boundary=1234567890123456789012345678\n' +
'testing Draft msg\n' +
'--1234567890123456789012345678--\n';
var draftBody = Utilities.base64Encode(raw);
var params = {method:"post",
contentType: "application/json",
headers: {"Authorization": "Bearer " + ScriptApp.getOAuthToken()},
muteHttpExceptions:true,
payload:JSON.stringify({
"message": {
"raw": draftBody
}
})
};
var resp = UrlFetchApp.fetch("https://www.googleapis.com/gmail/v1/users/me/drafts", params);
Logger.log(resp.getContentText());
It works great, BUT I want to embedd some image in the message body, without linking to external URL, so it always shows up, it's not blocked by some email clients, including Gmail. How to do that?