Skip to content

Commit

Permalink
commit
Browse files Browse the repository at this point in the history
  • Loading branch information
1s-sky committed Nov 19, 2021
1 parent 40c8354 commit a4e5f02
Show file tree
Hide file tree
Showing 2 changed files with 377 additions and 0 deletions.
185 changes: 185 additions & 0 deletions seungwon/calender.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,185 @@
<!DOCTYPE html>
<html>
<head>
<title>Google Calendar API Quickstart</title>
<meta charset="utf-8" />
</head>
<body>
<p>Google Calendar API 최근 일정 보기</p>

<!--Add buttons to initiate auth sequence and sign out-->
<button id="authorize_button" style="display: none;">연동하기</button>
<button id="signout_button" style="display: none;">로그아웃</button>

<pre id="content" style="white-space: pre-wrap;"></pre>

<script type="text/javascript">
// Client ID and API key from the Developer Console
var CLIENT_ID = '692904107411-54rl8q8jtj2oioth3kb4t4ssihj5db84.apps.googleusercontent.com';
var API_KEY = 'AIzaSyBNvUHVaiJtACI6H8F43MrXzeO3doLqTNE';

// Array of API discovery doc URLs for APIs used by the quickstart
var DISCOVERY_DOCS = ["https://www.googleapis.com/discovery/v1/apis/calendar/v3/rest"];

// Authorization scopes required by the API; multiple scopes can be
// included, separated by spaces.
var SCOPES = "https://www.googleapis.com/auth/calendar.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';
listUpcomingEvents();
} 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 the summary and start datetime/date of the next ten events in
* the authorized user's calendar. If no events are found an
* appropriate message is printed.
*/
function listUpcomingEvents() {
gapi.client.calendar.events.list({
'calendarId': 'primary',
'timeMin': (new Date()).toISOString(),
'showDeleted': false,
'singleEvents': true,
'maxResults': 10,
'orderBy': 'startTime'
}).then(function(response) {
var events = response.result.items;
appendPre('Upcoming events:');

if (events.length > 0) {
for (i = 0; i < events.length; i++) {
var event = events[i];
var when = event.start.dateTime;
if (!when) {
when = event.start.date;
}
appendPre(event.summary + ' (' + when + ')')
}
} else {
appendPre('No upcoming events found.');
}
});
}

// Refer to the JavaScript quickstart on how to setup the environment:
// https://developers.google.com/calendar/quickstart/js
// Change the scope to 'https://www.googleapis.com/auth/calendar' and delete any
// stored credentials.

var event = {
'summary': 'Google I/O 2015',
'location': '800 Howard St., San Francisco, CA 94103',
'description': 'A chance to hear more about Google\'s developer products.',
'start': {
'dateTime': '2015-05-28T09:00:00-07:00',
'timeZone': 'America/Los_Angeles'
},
'end': {
'dateTime': '2015-05-28T17:00:00-07:00',
'timeZone': 'America/Los_Angeles'
},
'recurrence': [
'RRULE:FREQ=DAILY;COUNT=2'
],
'attendees': [
{'email': '[email protected]'},
{'email': '[email protected]'}
],
'reminders': {
'useDefault': false,
'overrides': [
{'method': 'email', 'minutes': 24 * 60},
{'method': 'popup', 'minutes': 10}
]
}
};

var request = gapi.client.calendar.events.insert({
'calendarId': 'primary',
'resource': event
});

request.execute(function(event) {
appendPre('Event created: ' + event.htmlLink);
});


</script>

<script async defer src="https://apis.google.com/js/api.js"
onload="this.onload=function(){};handleClientLoad()"
onreadystatechange="if (this.readyState === 'complete') this.onload()">
</script>

</body>
</html>
192 changes: 192 additions & 0 deletions seungwon/gmail.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,192 @@
<!doctype html>
<html>
<head>
<title>Gmail API demo</title>
<meta charset="UTF-8">

<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">
<style>
iframe {
width: 100%;
border: 0;
min-height: 80%;
height: 600px;
display: flex;
}
</style>
</head>
<body>
<div class="container">
<h1>Gmail API 사용예시</h1>

<button id="authorize-button" class="btn btn-primary hidden">Authorize</button>

<table class="table table-striped table-inbox hidden">
<thead>
<tr>
<th>From</th>
<th>Subject</th>
<th>Date/Time</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>

<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>

<script type="text/javascript">
var clientId = '692904107411-54rl8q8jtj2oioth3kb4t4ssihj5db84.apps.googleusercontent.com';
var apiKey = 'AIzaSyBNvUHVaiJtACI6H8F43MrXzeO3doLqTNE';
var scopes = 'https://www.googleapis.com/auth/gmail.readonly';

function handleClientLoad() {
gapi.client.setApiKey(apiKey);
window.setTimeout(checkAuth, 1);
}

function checkAuth() {
gapi.auth.authorize({
client_id: clientId,
scope: scopes,
immediate: true
}, handleAuthResult);
}

function handleAuthClick() {
gapi.auth.authorize({
client_id: clientId,
scope: scopes,
immediate: false
}, handleAuthResult);
return false;
}

function handleAuthResult(authResult) {
if(authResult && !authResult.error) {
loadGmailApi();
$('#authorize-button').remove();
$('.table-inbox').removeClass("hidden");
} else {
$('#authorize-button').removeClass("hidden");
$('#authorize-button').on('click', function(){
handleAuthClick();
});
}
}

function loadGmailApi() {
gapi.client.load('gmail', 'v1', displayInbox);
}

function displayInbox() {
var request = gapi.client.gmail.users.messages.list({
'userId': 'me',
'labelIds': 'INBOX',
'maxResults': 10
});

request.execute(function(response) {
$.each(response.messages, function() {
var messageRequest = gapi.client.gmail.users.messages.get({
'userId': 'me',
'id': this.id
});

messageRequest.execute(appendMessageRow);
});
});
}

function appendMessageRow(message) {
$('.table-inbox tbody').append(
'<tr>\
<td>'+getHeader(message.payload.headers, 'From')+'</td>\
<td>\
<a href="#message-modal-' + message.id +
'" data-toggle="modal" id="message-link-' + message.id+'">' +
getHeader(message.payload.headers, 'Subject') +
'</a>\
</td>\
<td>'+getHeader(message.payload.headers, 'Date')+'</td>\
</tr>'
);

$('body').append(
'<div class="modal fade" id="message-modal-' + message.id +
'" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">\
<div class="modal-dialog modal-lg">\
<div class="modal-content">\
<div class="modal-header">\
<button type="button"\
class="close"\
data-dismiss="modal"\
aria-label="Close">\
<span aria-hidden="true">&times;</span></button>\
<h4 class="modal-title" id="myModalLabel">' +
getHeader(message.payload.headers, 'Subject') +
'</h4>\
</div>\
<div class="modal-body">\
<iframe id="message-iframe-'+message.id+'" srcdoc="<p>Loading...</p>">\
</iframe>\
</div>\
</div>\
</div>\
</div>'
);

$('#message-link-'+message.id).on('click', function(){
var ifrm = $('#message-iframe-'+message.id)[0].contentWindow.document;
$('body', ifrm).html(getBody(message.payload));
});
}

function getHeader(headers, index) {
var header = '';

$.each(headers, function(){
if(this.name === index){
header = this.value;
}
});
return header;
}

function getBody(message) {
var encodedBody = '';
if(typeof message.parts === 'undefined')
{
encodedBody = message.body.data;
}
else
{
encodedBody = getHTMLPart(message.parts);
}
encodedBody = encodedBody.replace(/-/g, '+').replace(/_/g, '/').replace(/\s/g, '');
return decodeURIComponent(escape(window.atob(encodedBody)));
}

function getHTMLPart(arr) {
for(var x = 0; x <= arr.length; x++)
{
if(typeof arr[x].parts === 'undefined')
{
if(arr[x].mimeType === 'text/html')
{
return arr[x].body.data;
}
}
else
{
return getHTMLPart(arr[x].parts);
}
}
return '';
}
</script>
<script src="https://apis.google.com/js/client.js?onload=handleClientLoad"></script>
</body>
</html>

0 comments on commit a4e5f02

Please sign in to comment.