Skip to content

Commit

Permalink
Feat: AiScriptでリモートサーバーのAPIを叩く関数を追加 (#11887)
Browse files Browse the repository at this point in the history
* add Mk:apiExternal

* fix

* lint

* Update CHANGELOG.md

* Update api.ts

* add apiExternal()

* add apiExternal()

* allow / ambiguity

* use os.apiExternal()

* add checks

* fix url
  • Loading branch information
FineArchs authored Sep 29, 2023
1 parent b55ffa2 commit f269841
Show file tree
Hide file tree
Showing 4 changed files with 58 additions and 3 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,7 @@
- Feat: Playで直接投稿フォームを埋め込めるように(`Ui:C:postForm`)
- Feat: クライアントを起動している間、デバイスの画面が自動でオフになるのを防ぐオプションを追加
- Feat: 新しい実績を追加
- Feat: リモートサーバーのAPIを叩く用の関数を追加(`Mk:apiExternal`
- Enhance: ノート詳細ページでリノート一覧、リアクション一覧タブを追加
- ノートのメニューからは当該項目は消えました
- Enhance: センシティブなメディアを目立たせる設定を追加
Expand Down
4 changes: 2 additions & 2 deletions packages/frontend/src/os.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@

// TODO: なんでもかんでもos.tsに突っ込むのやめたいのでよしなに分割する

import { pendingApiRequestsCount, api, apiGet } from '@/scripts/api.js';
export { pendingApiRequestsCount, api, apiGet };
import { pendingApiRequestsCount, api, apiExternal, apiGet } from '@/scripts/api.js';
export { pendingApiRequestsCount, api, apiExternal, apiGet };
import { Component, markRaw, Ref, ref, defineAsyncComponent } from 'vue';
import { EventEmitter } from 'eventemitter3';
import insertTextAtCursor from 'insert-text-at-cursor';
Expand Down
10 changes: 10 additions & 0 deletions packages/frontend/src/scripts/aiscript/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,16 @@ export function createAiScriptEnv(opts) {
return values.ERROR('request_failed', utils.jsToVal(err));
});
}),
'Mk:apiExternal': values.FN_NATIVE(async ([host, ep, param, token]) => {
utils.assertString(host);
utils.assertString(ep);
if (token) utils.assertString(token);
return os.apiExternal(host.value, ep.value, utils.valToJs(param), token?.value).then(res => {
return utils.jsToVal(res);
}, err => {
return values.ERROR('request_failed', utils.jsToVal(err));
});
}),
'Mk:save': values.FN_NATIVE(([key, value]) => {
utils.assertString(key);
miLocalStorage.setItem(`aiscript:${opts.storageKey}:${key.value}`, JSON.stringify(utils.valToJs(value)));
Expand Down
46 changes: 45 additions & 1 deletion packages/frontend/src/scripts/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ export const pendingApiRequestsCount = ref(0);

// Implements Misskey.api.ApiClient.request
export function api<E extends keyof Misskey.Endpoints, P extends Misskey.Endpoints[E]['req']>(endpoint: E, data: P = {} as any, token?: string | null | undefined, signal?: AbortSignal): Promise<Misskey.Endpoints[E]['res']> {
if (endpoint.includes('://')) throw new Error('invalid endpoint');
pendingApiRequestsCount.value++;

const onFinally = () => {
Expand All @@ -23,7 +24,50 @@ export function api<E extends keyof Misskey.Endpoints, P extends Misskey.Endpoin
if (token !== undefined) (data as any).i = token;

// Send request
window.fetch(endpoint.indexOf('://') > -1 ? endpoint : `${apiUrl}/${endpoint}`, {
window.fetch(`${apiUrl}/${endpoint}`, {
method: 'POST',
body: JSON.stringify(data),
credentials: 'omit',
cache: 'no-cache',
headers: {
'Content-Type': 'application/json',
},
signal,
}).then(async (res) => {
const body = res.status === 204 ? null : await res.json();

if (res.status === 200) {
resolve(body);
} else if (res.status === 204) {
resolve();
} else {
reject(body.error);
}
}).catch(reject);
});

promise.then(onFinally, onFinally);

return promise;
}

export function apiExternal<E extends keyof Misskey.Endpoints, P extends Misskey.Endpoints[E]['req']>(hostUrl: string, endpoint: E, data: P = {} as any, token?: string | null | undefined, signal?: AbortSignal): Promise<Misskey.Endpoints[E]['res']> {
if (!/^https?:\/\//.test(hostUrl)) throw new Error('invalid host name');
if (endpoint.includes('://')) throw new Error('invalid endpoint');
pendingApiRequestsCount.value++;

const onFinally = () => {
pendingApiRequestsCount.value--;
};

const promise = new Promise<Misskey.Endpoints[E]['res'] | void>((resolve, reject) => {
// Append a credential
(data as any).i = token;

const fullUrl = (hostUrl.slice(-1) === '/' ? hostUrl.slice(0, -1) : hostUrl)
+ '/api/' + (endpoint.slice(0, 1) === '/' ? endpoint.slice(1) : endpoint);
// Send request
window.fetch(fullUrl, {
method: 'POST',
body: JSON.stringify(data),
credentials: 'omit',
Expand Down

0 comments on commit f269841

Please sign in to comment.