I have a problem with displaying decrypted messages using the Gmail API, can someone help me and explain how to do it to make everything work properly.
The error that is displayed to me:
PS: Sorry for all grammar mistakes, i am not very advanced in English yet
I'm try decrypt messages using atob & i'm try split messages and use atob.
CodePudding user response:
The mistake you have is that somewhere you have a call to
atob(window)
however, the function expects a Base64 and converts it to a number.
You will need to find out what the intention of the code was and replace the parameter passed to atob
with the proper Base64 value.
CodePudding user response:
My HTML code:
<!--
Copyright 2018 Google LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<!-- [START gmail_quickstart] -->
<!DOCTYPE html>
<html>
<head>
<title>Gmail API Quickstart</title>
<meta charset="utf-8" />
<link rel="stylesheet" href="css/mail-layout.css">
</head>
<body>
<p>Gmail API Quickstart</p>
<!--Add buttons to initiate auth sequence and sign out-->
<button id="authorize_button" style="display: none;">Authorize</button>
<button id="signout_button" style="display: none;">Sign Out</button>
<pre id="content" style="white-space: pre-wrap;"></pre>
<pre id="content2" style="white-space: pre-wrap;"></pre>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP u1T9qYdvdihz0PPSiiqn/ /3e7Jo4EaG7TubfWGUrMQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script type="text/javascript" src="api.js"></script>
<script type="text/javascript" src="js-api/functions.js"></script>
<script async defer src="https://apis.google.com/js/api.js"
onl oad="this.onload=function(){};handleClientLoad()"
onreadystatechange="if (this.readyState === 'complete') this.onload()">
</script>
</body>
</html>
<!-- [END gmail_quickstart] -->
api.js code:
// Client ID and API key from the Developer Console
var CLIENT_ID = '231998038190-410ifknsn879tle6uvmi8o0o3tlqtbt1.apps.googleusercontent.com';
var API_KEY = 'AIzaSyDiivbSVIZd0U5GChXELNswd9iGLGtL6QQ';
// Array of API discovery doc URLs for APIs used by the quickstart
var DISCOVERY_DOCS = ["https://www.googleapis.com/discovery/v1/apis/gmail/v1/rest"];
// Authorization scopes required by the API; multiple scopes can be
// included, separated by spaces.
var SCOPES = 'https://www.googleapis.com/auth/gmail.readonly';
var authorizeButton = document.getElementById('authorize_button');
var signoutButton = document.getElementById('signout_button');
/**
* On load, called to load the auth2 library and API client library.
*/
function handleClientLoad() {
gapi.load('client:auth2', initClient);
}
/**
* Initializes the API client library and sets up sign-in state
* listeners.
*/
function initClient() {
gapi.client.init({
apiKey: API_KEY,
clientId: CLIENT_ID,
discoveryDocs: DISCOVERY_DOCS,
scope: SCOPES
}).then(function () {
// Listen for sign-in state changes.
gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus);
// Handle the initial sign-in state.
updateSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get());
authorizeButton.onclick = handleAuthClick;
signoutButton.onclick = handleSignoutClick;
}, function(error) {
appendPre(JSON.stringify(error, null, 2));
});
}
/**
* Called when the signed in status changes, to update the UI
* appropriately. After a sign-in, the API is called.
*/
function updateSigninStatus(isSignedIn) {
if (isSignedIn) {
authorizeButton.style.display = 'none';
signoutButton.style.display = 'block';
//listLabels();
readMessages();
} else {
authorizeButton.style.display = 'block';
signoutButton.style.display = 'none';
}
}
/**
* Sign in the user upon button click.
*/
function handleAuthClick(event) {
gapi.auth2.getAuthInstance().signIn();
}
/**
* Sign out the user upon button click.
*/
function handleSignoutClick(event) {
gapi.auth2.getAuthInstance().signOut();
}
/**
* Append a pre element to the body containing the given message
* as its text node. Used to display the results of the API call.
*
* @param {string} message Text to be placed in pre element.
*/
function appendPre(message) {
var pre = document.getElementById('content');
var textContent = document.createTextNode(message '\n');
pre.appendChild(textContent);
}
/**
* Print all Labels in the authorized user's inbox. If no labels
* are found an appropriate message is printed.
*/
function listLabels() {
/*gapi.client.gmail.users.labels.list({
'userId': 'me'
}).then(function(response) {
var labels = response.result.labels;
appendPre('Labels:');
if (labels && labels.length > 0) {
for (i = 0; i < labels.length; i ) {
var label = labels[i];
appendPre(label.name)
}
} else {
appendPre('No Labels found.');
}
});*/
}
js-api/functions.js code
function append(subject, text){
$("body").prepend("<div class='mail_box' id='mail_box" i "'></div>")
$("#mail_box" i).append("<div class='message'></div>")
$("#mail_box" i " .message").append("<div class='subject'>" subject "</div>")
$("#mail_box" i " .message").append("<div class='text'>" text "</div>")
i
}
function splitStringBySegmentLength(source, segmentLength) {
if (!segmentLength || segmentLength < 1) throw Error('Segment length must be defined and greater than/equal to 1');
const target = [];
for (
const array = Array.from(source);
array.length;
target.push(array.splice(0,segmentLength).join('')));
return target;
}
function debug1Message(msgID){
gapi.client.gmail.users.messages.get({
'userId': 'me',
'id': msgID
}).then(function(response) {
var output = response.result;
console.warn("âš ï¸ Debug [Message: msgID:" msgID " ]");
console.warn(output)
});
}
function read1Message(msgID){
gapi.client.gmail.users.messages.get({
'userId': 'me',
'id': msgID
}).then(function(response) {
var output = response.result;
for (var headerIndex = 0; headerIndex < output.payload.headers.length; headerIndex ) {
if (response.result.payload.headers[headerIndex].name == 'Subject') {
x = output.payload.headers[headerIndex].value;
var subject = x;
}
}
console.warn("âš ï¸ Debug [msgID]:" msgID);
//var messageHTML = output.payload.parts[1].body.data
try{
var ab = output.payload.parts.length
console.warn("âš :" ab)
for (var headerIndex = 0; headerIndex < ab; headerIndex ) {
if (response.result.payload.parts[headerIndex].mimeType == 'text/html') {
x = output.payload.parts[headerIndex].body.data;
var messageHTML = x;
}
}
}
catch(err){
try{
var messageHTML = output.payload.body.data;
}
catch(err2){
var messageHTML = "Broken/Expired message"
}
}
//var messageHTMLdecrypted = atob(messageHTML)
var result = []
/*result.push(subject)
result.push(messageHTML)*/
console.log("Subject:", subject)
//console.log("Messsage (encrypted):", messageHTML)
//console.log("Messsage (HTML):", messageHTMLdecrypted)
//document.getElementById("content").innerHTML = x
$("#content").html(subject ";?;" messageHTML)
y = $("#content").html().split(";?;")
z = y[1].replaceAll("-", " ")
//z = z.replaceAll(" ", " ;")
//console.log(y)
if (y && y.length > 0) {
/*for (i = 0; i < y.length; i ) {
var tmp = z[i];
/*console.log(z)*/
/*var tmp_decoded = atob(z.split(" ")[i]) ///FAILED
tmp_decoded = tmp_decoded.replaceAll(";", " ")
$("#content2").append(tmp_decoded)
console.warn(tmp_decoded)
}*/
//zlen = z.length / 100 1
//console.error(zlen)
//var zout = splitStringBySegmentLength(z, zlen)
//console.log(zout)
/*for (i = 0; i < zout.length; i ){
console.warn(zout[i]) //PASSED
//var tmp_decoded = atob(zout[i]) ///FAILED
//console.warn(tmp_decoded)
//$("#content2").append(tmp_decoded)
}*/
console.error(z)
try{
var tmp_decoded = atob(z);
}
catch(err){
z2 = z.split("_");
for (i = 0; i < z2.length; i ){
$("#content2").html("")
var tmp_decoded = atob(z2[i])
var old = $("#content2").html()
$("#content2").html(old tmp_decoded)
}
}
$("#content2").append(tmp_decoded)
var decoded = $("#content2").html()
var msg = y[0]
append(msg, decoded)
$("#content2").html("")
} else {
appendPre('Message Error receive data');
}
});
}
function readMessages(){
gapi.client.gmail.users.messages.list({
'userId': 'me'
}).then(function(response) {
var output = response.result.messages;
console.log(output)
if (output && output.length > 0) {
for (i = 0; i < output.length; i ) {
var msgID = output[i].id;
read1Message(msgID)
}
} else {
appendPre('No Labels found.');
}
});
}