Skip to content

Commit

Permalink
change api endpoint
Browse files Browse the repository at this point in the history
  • Loading branch information
amay077 committed Jun 23, 2024
1 parent 558b043 commit 220f280
Show file tree
Hide file tree
Showing 5 changed files with 93 additions and 62 deletions.
2 changes: 1 addition & 1 deletion src/App.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
} else if (state == null && code) {
(async () => {
const res = await fetch(`${Config.API_ENDPOINT}/token?code=${code}`)
const res = await fetch(`${Config.API_ENDPOINT}/foursquare_token?code=${code}`)
const jsonData = await res.json();
const url = new URL(window.location.href);
Expand Down
4 changes: 2 additions & 2 deletions src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
const config_dev = {
CLIENT_ID: 'JXKR3OYSVKYPR4YSIYFUXUASGG2SXDIR1I2XDLIWIAMUK2ES',
REDIRECT_URI: 'http://localhost:8080/#/auth',
API_ENDPOINT: `http://localhost:9999/.netlify/functions`,
API_ENDPOINT: `http://localhost:9000/.netlify/functions`,

post_targets: {
mastodon: {
Expand All @@ -27,7 +27,7 @@ const config_dev = {
const config_prod = {
CLIENT_ID: 'UBWPEWEM3L1XHICEZ0TJWOHFQ3QZ0KC3XZPHUXRRVWL044ZU',
REDIRECT_URI: 'https://amay077.github.io/swarm-check-ins/#/auth',
API_ENDPOINT: `https://swarm-check-ins-api.netlify.app/.netlify/functions`,
API_ENDPOINT: `https://pppost-api.netlify.app/.netlify/functions`,

post_targets: {
mastodon: {
Expand Down
89 changes: 38 additions & 51 deletions src/lib/MainContent.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -40,32 +40,7 @@
const url = new URL(window.location.href);
const params = new URLSearchParams(url.search);
if (params.get('state') == 'twitter_callback' && params.has('code')) {
const code = params.get('code') ?? '';
const res = await fetch(`${Config.API_ENDPOINT}/twitter_token?code=${code}`)
if (res.ok) {
const data = await res.json();
postSettings.twitter = { type: 'twitter', title: 'Twitter', enabled: true, access_token_response: { refresh_token: data.refresh_token } };
savePostSetting(postSettings.twitter);
postTo.twitter = true;
alert('Twitter に接続しました。');
} else {
console.error(`twitter 接続エラー -> res:`, res);
alert('Twitter に接続できませんでした。');
}
const url = new URL(window.location.href);
params.delete('code');
params.delete('state');
url.hash = '';
url.search = params.toString();
history.replaceState(null, '', url.toString());
}
// アクセストークンを使用してチェックイン一覧を取得する
const response = await fetch(`https://api.foursquare.com/v2/users/self/checkins?oauth_token=${accessToken}&v=20230823&limit=100`);
if (!response.ok) {
Expand Down Expand Up @@ -146,7 +121,7 @@
}
break;
case 'twitter':
if (!(await postToTwritter(text))) {
if (!(await postToTwritter(text, []))) {
errors.push('Twitter');
}
break;
Expand Down Expand Up @@ -294,33 +269,45 @@
}
};
const postToTwritter = async (text: string): Promise<boolean> => {
try {
const settings = postSettings.twitter!;
const refresh_token = settings.access_token_response.refresh_token;
const res = await fetch(`${Config.API_ENDPOINT}/twitter_post`, {
method: 'POST',
headers: {
'Content-Type': 'text/plain',
},
body: JSON.stringify({ refresh_token, text }),
});
const postToTwritter = async (text: string, images: string[]): Promise<boolean> => {
try {
const settings = postSettings.twitter!;
const token = settings.token_data.token;
const imgs: string[] = [];
// for (const dataURI of images) {
// const image = dataURI.split(',')[1]
// const imageUrl = await uploadImage(image);
// if (imageUrl != null) {
// imgs.push(imageUrl);
// }
// }
/*
const images: string[] = [
'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAgAAAAIAQMAAAD+wSzIAAAABlBMVEX///+/v7+jQ3Y5AAAADklEQVQI12P4AIX8EAgALgAD/aNpbtEAAAAASUVORK5CYII',
];
*/
const res = await fetch(`${Config.API_ENDPOINT}/twitter_post`, {
method: 'POST',
headers: {
'Content-Type': 'text/plain',
},
body: JSON.stringify({ token, text, images: imgs }),
});
if (res.ok) {
const resJson = await res.json();
console.log(`FIXME h_oku 後で消す -> postToTwritter -> resJson:`, resJson);
settings.access_token_response.refresh_token = resJson.refresh_token;
savePostSetting(settings);
} else {
return false;
}
return true;
} catch (error) {
console.error(`postToMastodon -> error:`, error);
return false;
if (res.ok) {
const resJson = await res.json();
console.log(`FIXME 後で消す -> postToTwritter -> resJson:`, resJson);
} else {
return false;
}
};
return true;
} catch (error) {
console.error(`postToMastodon -> error:`, error);
return false;
}
};
const onChangePostSettings = () => {
postSettings.mastodon = loadPostSetting('mastodon');
Expand Down
56 changes: 50 additions & 6 deletions src/lib/TwitterConnection.svelte
Original file line number Diff line number Diff line change
@@ -1,21 +1,57 @@
<script lang="ts">
import { createEventDispatcher } from "svelte";
import { Config } from "../config";
import { deletePostSetting, loadPostSetting } from "./func";
import { deletePostSetting, loadPostSetting, savePostSetting } from "./func";
const dispatch = createEventDispatcher<{ onChange: void }>();
let expanded = false;
let postSettings = loadPostSetting('twitter');
const onConnectToTwitter = () => {
let oAuthToken = '';
let pinCode = '';
let oAuthData = '';
const url = `https://twitter.com/i/oauth2/authorize?response_type=code&client_id=${Config.post_targets.twitter.client_id}&redirect_uri=${Config.post_targets.twitter.redirect_uri}&scope=tweet.read%20tweet.write%20users.read%20offline.access&state=twitter_callback&code_challenge=challenge&code_challenge_method=plain`;
const onConnectToTwitter = async () => {
const res = await fetch(`${Config.API_ENDPOINT}/twitter_auth`, {
method: 'POST',
headers: {
'Content-Type': 'text/plain',
},
body: JSON.stringify({ }),
});
const { url, oauth_token, data } = await res.json();
oAuthToken = oauth_token;
oAuthData = data;
// const redirect_uri = encodeURIComponent(Config.post_targets.twitter.redirect_uri);
// const url = `https://twitter.com/i/oauth2/authorize?response_type=code&client_id=${Config.post_targets.twitter.client_id}&redirect_uri=${redirect_uri}&scope=tweet.read%20tweet.write%20users.read%20offline.access&state=twitter_callback&code_challenge=challenge&code_challenge_method=plain`;
// url をこのタブで開く
window.open(url, '_self');
// url を別タブで開く
window.open(url, '_blank');
};
export async function onApplyTwitterPinCode() {
const res = await fetch(`${Config.API_ENDPOINT}/twitter_token?code=${pinCode}&oauth_token=${oAuthToken}&data=${oAuthData}`);
pinCode = '';
if (res.ok) {
const data = await res.json();
postSettings = { type: 'twitter', title: 'Twitter', enabled: true, token_data: {
token: data.token,
}};
savePostSetting(postSettings);
dispatch('onChange');
alert('Twitter に接続しました。');
} else {
console.error(`twitter 接続エラー -> res:`, res);
alert('Twitter に接続できませんでした。');
}
}
</script>

<div>
Expand Down Expand Up @@ -51,10 +87,18 @@
{:else}
<div class="d-flex flex-column gap-1">
<div class="d-flex flex-column gap-1">
<div class="d-flex flex-row gap-1">
<div class="d-flex flex-row align-items-center gap-1">
<span>1.</span>
<button class="btn btn-sm btn-primary" style="width: 60px;" on:click={onConnectToTwitter}>接続</button>
</div>
</div>
<div class="d-flex flex-column gap-1">
<span>2.PINコードを貼り付けて設定</span>
<div class="d-flex flex-row gap-1">
<input class="form-control form-control-sm" type="text" bind:value={pinCode}>
<button class="btn btn-sm btn-primary" disabled={pinCode?.length <= 0} style="width: 60px;" on:click={onApplyTwitterPinCode}>設定</button>
</div>
</div>
</div>
{/if}

Expand Down
4 changes: 2 additions & 2 deletions src/lib/func.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,8 @@ export type SettingDataTwitter = {
type: 'twitter',
title: 'Twitter',
enabled: boolean,
access_token_response: {
refresh_token: string,
token_data: {
token: string,
}
};

Expand Down

0 comments on commit 220f280

Please sign in to comment.