Edit an existing Pastebin document via API - http

I am trying to write a function in LUA to edit my pastebin code.
I can use this code to make a HTTP post:
http.post(string url, string postData [, table headers])
I can also use this code for a HTTP get:
http.get(string url [, table headers])
on the Pastebin website https://pastebin.com/api are information about using the API.
I am not sure, if this website can help me to solve my problem.
Does someone know how to fill the headers table?
this is the program i tried:
headers = {}
headers["api_dev_key"]= 'myDevKey...'; // your api_developer_key
headers["api_paste_code"] = 'my edited text'; // your paste text
headers["api_paste_private"] = '0'; // 0=public 1=unlisted 2=private
headers["api_paste_name"] = 'justmyfilename.php'; // name or title of your paste
headers["api_paste_expire_date"] = '10M';
headers["api_paste_format"] = 'php';
headers["api_user_key"] = ''; // if an invalid or expired api_user_key is used, an error will spawn. If no api_user_key is used, a guest paste will be created
headers["api_paste_name"] = myPastebinName;
headers["api_paste_code"] = myPastebinPassword;
http.get("https://pastebin.com/edit/dQMDfbkM", headers)
unfortunately this is not working and on the pastebin API help site is no exsample for editing a paste. just for creating a new one.
for me it is also not clear if I have to use post or get

There is no API for editing pastes directly.
You can only delete old paste and create new with updated text.

Related

Download an externalReference from PlannerTask using the Graph API

I'd like to download a file attached to a PlannerTask. I already have the external references but I can't figure out how to access the file.
An external reference is a JSON object like this:
{
"https%3A//contoso%2Esharepoint%2Ecom/sites/GroupName/Shared%20Documents/AnnualReport%2Epptx":
{
// ... snip ...
}
}
I've tried to use the following endpoint
GET /groups/{group-id}/drive/root:/sites/GroupName/Shared%20Documents/AnnualReport%2Epptx
but I get a 404 response. Indeed, when I use the query in Graph Explorer it gives me a warning about "Invalid whitespace in URL" (?).
A workaround that I've found is to use the search endpoint to look for files like this:
GET /groups/{group-id}/drive/root/search(q='AnnualReport.pptx')
and hope the file name is unique.
Anyway, with both methods I need extra information (ie. the group-id) that may not be readily available by the time I have the external reference object.
What is the proper way to get a download url for a driveItem that is referenced by an external reference object in a PlannerTask?
Do I really need the group-id to access such file?
The keys in external references are webUrl instances, so they can be used with the /shares/ endpoint. See this answer for details on how to do it.
When you get a driveItem object, the download url is available from AdditionalData: driveItem.AdditionalData["#microsoft.graph.downloadUrl"]. You can use WebClient.DownloadFile to download the file on the local machine.
Here is the final code:
var remoteUri = "https%3A//contoso%2Esharepoint%2Ecom/sites/GroupName/Shared%20Documents/AnnualReport%2Epptx";
var localFile = "/tmp/foo.pptx";
string sharingUrl = remoteUri;
string base64Value = System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(sharingUrl));
string encodedUrl = "u!" + base64Value.TrimEnd('=').Replace('/','_').Replace('+','-');
DriveItem driveItem = m_graphClient
.Shares[encodedUrl]
.DriveItem
.Request()
.GetAsync().Result;
using (WebClient client = new WebClient())
{
client.DownloadFile(driveItem.AdditionalData["#microsoft.graph.downloadUrl"].ToString(),
localFile);
}

POST method to upload file to Azure storage - what to return

I am creating an app where
user can upload the text file and then
find most used word and change that word in text and
show the changed text to the user.
if it is possible, I would like to
get the file’s text content before uploading when Post method is being called and save that content
so I add the “DownloadTextAsync()” method inside of the POST method, but it seems like I am calling this method to the wrong subject?
[HttpPost("UploadText")]
public async Task<IActionResult> Post(List<IFormFile> files)
{
string connectionString = Environment.GetEnvironmentVariable("mykeystringhere");
// Create a BlobServiceClient object which will be used to create a container client
BlobServiceClient blobServiceClient = new BlobServiceClient(connectionString);
//Create a unique name for the container
string containerName = "textdata" + Guid.NewGuid().ToString();
// Create the container and return a container client object
BlobContainerClient containerClient = await blobServiceClient.CreateBlobContainerAsync(containerName);
// Create a local file in the ./data/ directory for uploading and downloading
string localPath = "./data/";
string fileName = "textfiledata" + Guid.NewGuid().ToString() + ".txt";
string localFilePath = Path.Combine(localPath, fileName);
// Get a reference to a blob
BlobClient blobClient = containerClient.GetBlobClient(fileName);
// Open the file and upload its data
using FileStream uploadFileStream = System.IO.File.OpenRead(localFilePath);
await blobClient.UploadAsync(uploadFileStream, true);
uploadFileStream.Close();
string downloadFilePath = localFilePath.Replace(".txt", "DOWNLOAD.txt");
// Get the blob file as text
string contents = blobClient.DownloadTextAsync().Result;
//return the string
return contents;
//if (uploadSuccess)
// return View("UploadSuccess");
//else
// return View("UploadError");
}
The issues I am having are
I understood that ‘blobClient’ is the reference to the blob, where I can get the file’s data but this must be wrong?
Also it seems like I cannot use “CloudBlobContainer” nor the “CloudBlockBlob blob”. Is it because inside of the POST method, the blob has been just initialized and does not exist when these twos are executed?
Also when I test the POST method, the console throws “Refused to load the font '' because it violates the following Content Security Policy directive: "default-src 'none'". Note that 'font-src' was not explicitly set, so 'default-src' is used as a fallback.” which I googled but have no idea what it means?
I have tried different ways but keep getting CANNOT POST/“ But could not really find the solid anwers. Could this be related to my POST method?
I understood that ‘blobClient’ is the reference to the blob, where I
can get the file’s data but this must be wrong?
That's correct in a sense that you can use blobClient to perform operations on blob like upload/download etc. I am not sure why you say but this must be wrong.
Also it seems like I cannot use “CloudBlobContainer” nor the
“CloudBlockBlob blob”. Is it because inside of the POST method, the
blob has been just initialized and does not exist when these twos are
executed?
No, this is happening because you're using a newer version of SDK (version 12.x.x) and CloudBlobContainer and CloudBlockBlob are available in the older version of the SDK.
Also when I test the POST method, the console throws “Refused to load
the font '' because it violates the following Content Security Policy
directive: "default-src 'none'". Note that 'font-src' was not
explicitly set, so 'default-src' is used as a fallback.” which I
googled but have no idea what it means? I have tried different ways
but keep getting CANNOT POST/“ But could not really find the solid
anwers. Could this be related to my POST method?
Not sure why this is happening. You may want to ask a separate question for this and when you do, please include the HTML portion of your code as well.

unable to see header after fpdf creates file

I am working on a wordpress plugin,
I want to create a pdf file, For this I used fpdf
By using this code I am able to generate pdf and save it to server
require('fpdf/html_table.php');
$pdf=new PDF_HTML();
$questions = $_POST['question'];
$count = count($questions);
$quests = "";
$pdf->SetFont('times','',12);
$pdf->SetTextColor(50,60,100);
$pdf->AddPage('P');
$pdf->SetDisplayMode(real,'default');
$pdf->SetFontSize(12);
for($i=1;$i<=$count;$i++)
{
$qus_id = $questions[$i-1];
$get_q = "select * from `SelleXam_question` where `id`='$qus_id'";
$get_q = $wpdb->get_results($get_q);
$questf = "Quest $i : ".$get_q[0]->question;
$pdf->Cell(0, 10, $questf."\n");
$pdf->Ln();
}
$dir='C:/wamp/www/';
$filename= "filename.pdf";
$pdf ->Output($dir.$filename);
echo "Save PDF in folder";
But when it saved and displayed the messge Save PDF in Folder. I am unable to see the header part of the wordpress website.
Or when I use
$pdf->Output($filename,'D');
then is there any way that I can show the file in a link
When you are developing for Wordpress, you can't just echo text at any time. Wordpress has a whole series of actions it goes through to progressively generate the output rendered to the browser. If you generate output at an inappropriate time, you'll mess up Wordpress' ability to generate output at the right time.
If I were developing this, I'd have this function be called as a filter on the_content. Your output code would change to something like this:
function append_pdf_to_content($content) {
//Your existing code
$pdf->Output($filename, 'F');
$pdf_link = "<br><a href='$filename' download>Download PDF</a>"
return $content . $pdf_link;
}
add_filter('the_content', 'append_pdf_to_content');
If you wanted to use the D option, you'll need to link your users to a separate php page using a target='_blank' that calls the download. Otherwise the PDFs headers will override any headers Wordpress is trying to send.
BTW, you also might want to also take a look at mPDF, it's a fork of fpdf and remains in active development.

Query strip is removed from open graph url

In relation to this question: Dynamic generation of Facebook Open Graph meta tags
I have followed these instructions but the api seems to remove my query string so that the url passed into the aggregation contains none of my dynamic information. If I enter the url with the query string into the debugger it doesn't remove it and works fine. I can confirm my og:url meta tag does also contain the same query string not just the base url. What am I doing wrong?
I was having a similar issue and solved it like this:
So assuming you're doing your post request like it shows in the tutorial, youre Javascript probably looks something like this:
function postNewAction()
{
passString = '&object=http://yoursite.com/appnamespace/object.php';
FB.api('/me/APP_NAMESPACE:ACTION' + passString,'post',
function(response) {
if (!response || response.error) {
alert(response.error.message);
}
else {
alert('Post was successful! Action ID: ' + response.id);
}
}
);
}
And since you say you want to generate meta tags dynamically, you're probably adding a parameter to the url (passString) there like so:
passString = '&object=http://yoursite.com/appnamespace/object.php?user=' + someuser;
This is wrong.
What you need to do is to make the url a 'pretty url' and use htaccess to decipher it. So:
passString = '&object=http://yoursite.com/appnamespace/object/someuser';
Then your htaccess file will tell your site that that url actually equates to
http://yoursite.com/appnamespace/object/object.php?user=someuser
Then you can use GET to store the user parameter with php and insert it however you like into your meta tags.
In case youre wondering, in the og:url meta tag's content will be:
$url = 'http://yoursite.com/appnamespace/object/object.php?user=' . $_GET[$user];
Does that help?

Is there a way to wait for asynchronous apps-script function calls before continuing with code?

I am attempting to copy a document in drive, edit it and mail it. Basically like a mail merge.
I take a template document, make a copy, edit the copy and then email it.
Unfortunately the edits are not complete before the email code runs, so the email attaches the copied document before the edits have been made. Is there a way around this?
//make a copy of the template
var templateCopy = DriveApp.getFileById(templateID).makeCopy('newFile', DriveApp.getFolderById(targetFolderID));
//select the contents of the template
var copyBody = DocumentApp.openById(templateCopy.getId())
//replace text: set the date
copyBody.replaceText("%DATE%",'today')
//send email - the email that arrives does not have the date substitution, it still contains the %DATE% tag
GmailApp.sendEmail(targetAddress, 'eggs', 'eggs', {attachments:[copyBody.getAs(MimeType.PDF)]});
edit regarding possible duplicate: SpreadsheetApp.flush() is not relevant as we are not working with a spreadsheet.
Answer:
Use the saveAndClose() method of DocumentApp to force changes before continuing.
More Information:
As per the Apps Script documentation:
Saves the current Document. Causes pending updates to be flushed and applied.
The saveAndClose() method is automatically invoked at the end of script execution for each open editable Document.
A closed Document can't be edited. Use DocumentApp.openById() to reopen a given document for editing.
Implementation:
function documentStuff() {
//make a copy of the template
var templateCopy = DriveApp.getFileById(templateID).makeCopy('newFile',
DriveApp.getFolderById(targetFolderID)
);
//select the contents of the template
var copyBody = DocumentApp.openById(templateCopy.getId());
//replace text: set the date
copyBody.replaceText("%DATE%",'today');
copyBody.saveAndClose();
sendMail(targetAddress, DocumentApp.openById(templateCopy.getId()));
}
function sendMail(targetAddress, file) {
//send email - the email that arrives does not have the date substitution
// it still contains the %DATE% tag
GmailApp.sendEmail(targetAddress, 'eggs', 'eggs', {
attachments: [
file.getAs(MimeType.PDF)]
}
);
}
Splitting the Document and Gmail methods into separate functions also can help with this issue.
References:
Class DocumentApp
.saveAndClose() method of DocumentApp Class

Resources