paricafe/src/client/mios.ts

283 lines
6.9 KiB
TypeScript
Raw Normal View History

import autobind from 'autobind-decorator';
2018-02-21 14:05:19 -06:00
import Vue from 'vue';
2017-11-15 12:06:52 -06:00
import { EventEmitter } from 'eventemitter3';
2018-02-24 09:18:09 -06:00
2018-04-29 07:41:48 -05:00
import initStore from './store';
2020-02-19 15:08:49 -06:00
import { apiUrl, version } from './config';
import Progress from './scripts/loading';
2017-11-15 12:06:52 -06:00
import Stream from './scripts/stream';
2018-02-21 14:05:19 -06:00
2018-03-02 23:42:25 -06:00
//#region api requests
let spinner = null;
let pending = 0;
//#endregion
2017-11-15 12:06:52 -06:00
/**
* Misskey Operating System
*/
export default class MiOS extends EventEmitter {
2018-02-22 08:53:07 -06:00
public app: Vue;
2018-04-29 03:17:15 -05:00
public store: ReturnType<typeof initStore>;
2017-11-15 12:06:52 -06:00
/**
2017-11-16 10:24:44 -06:00
* A connection manager of home stream
2017-11-15 12:06:52 -06:00
*/
public stream: Stream;
2018-02-09 03:28:06 -06:00
2017-11-20 12:40:09 -06:00
/**
* A registration of service worker
*/
private swRegistration: ServiceWorkerRegistration = null;
@autobind
2018-02-26 04:23:53 -06:00
public signout() {
2018-05-26 23:49:09 -05:00
this.store.dispatch('logout');
2018-02-26 04:23:53 -06:00
location.href = '/';
}
2017-11-15 12:06:52 -06:00
/**
* Initialize MiOS (boot)
* @param callback A function that call when initialized
*/
@autobind
2020-02-12 14:08:01 -06:00
public async init(callback) {
const finish = () => {
callback();
2020-02-11 05:05:47 -06:00
this.store.dispatch('instance/fetch').then(() => {
// Init service worker
if (this.store.state.instance.meta.swPublickey) this.registerSw(this.store.state.instance.meta.swPublickey);
});
};
2018-04-29 03:17:15 -05:00
this.store = initStore(this);
2017-11-15 12:06:52 -06:00
// ユーザーをフェッチしてコールバックする
const fetchme = (token, cb) => {
let me = null;
// Return when not signed in
2020-02-14 08:59:54 -06:00
if (token == null || token === 'null') {
2017-11-15 12:06:52 -06:00
return done();
}
// Fetch user
2018-02-24 09:18:09 -06:00
fetch(`${apiUrl}/i`, {
2017-11-15 12:06:52 -06:00
method: 'POST',
body: JSON.stringify({
i: token
})
2017-11-16 10:24:44 -06:00
})
// When success
.then(res => {
2017-11-15 12:06:52 -06:00
// When failed to authenticate user
if (res.status !== 200 && res.status < 500) {
2018-02-26 04:23:53 -06:00
return this.signout();
2017-11-15 12:06:52 -06:00
}
2017-11-16 10:24:44 -06:00
// Parse response
2017-11-15 12:06:52 -06:00
res.json().then(i => {
me = i;
2018-04-07 13:58:11 -05:00
me.token = token;
2017-11-15 12:06:52 -06:00
done();
});
2017-11-16 10:24:44 -06:00
})
// When failure
.catch(() => {
2017-11-15 12:06:52 -06:00
// Render the error screen
document.body.innerHTML = '<div id="err">Oops!</div>';
2017-11-16 10:24:44 -06:00
2017-11-15 12:06:52 -06:00
Progress.done();
});
function done() {
if (cb) cb(me);
}
};
// フェッチが完了したとき
2018-05-26 23:49:09 -05:00
const fetched = () => {
2018-02-09 03:28:06 -06:00
this.emit('signedin');
2017-11-15 12:06:52 -06:00
2018-10-09 01:08:31 -05:00
this.initStream();
2017-11-15 12:06:52 -06:00
// Finish init
2020-02-12 14:08:01 -06:00
finish();
2017-11-15 12:06:52 -06:00
};
2017-11-20 16:06:36 -06:00
// キャッシュがあったとき
2018-05-26 23:49:09 -05:00
if (this.store.state.i != null) {
if (this.store.state.i.token == null) {
2018-04-07 14:44:59 -05:00
this.signout();
return;
}
2017-11-20 16:06:36 -06:00
// とりあえずキャッシュされたデータでお茶を濁して(?)おいて、
2018-05-26 23:49:09 -05:00
fetched();
2017-11-15 12:06:52 -06:00
// 後から新鮮なデータをフェッチ
2018-05-26 23:49:09 -05:00
fetchme(this.store.state.i.token, freshData => {
this.store.dispatch('mergeMe', freshData);
2017-11-15 12:06:52 -06:00
});
} else {
// Get token from localStorage
let i = localStorage.getItem('i');
// 連携ログインの場合用にCookieを参照する
if (i == null || i === 'null') {
i = (document.cookie.match(/igi=(\w+)/) || [null, null])[1];
}
2018-04-29 03:17:15 -05:00
fetchme(i, me => {
if (me) {
2018-05-26 23:49:09 -05:00
this.store.dispatch('login', me);
fetched();
2018-04-29 03:17:15 -05:00
} else {
2018-10-19 21:24:02 -05:00
this.initStream();
2018-04-29 03:17:15 -05:00
// Finish init
2020-02-12 14:08:01 -06:00
finish();
2018-04-29 03:17:15 -05:00
}
});
2017-11-15 12:06:52 -06:00
}
}
2018-10-09 01:08:31 -05:00
@autobind
private initStream() {
this.stream = new Stream(this);
}
2017-11-20 16:06:36 -06:00
/**
* Register service worker
*/
@autobind
2019-07-23 12:16:41 -05:00
private registerSw(swPublickey: string) {
2017-11-20 16:06:36 -06:00
// Check whether service worker and push manager supported
const isSwSupported =
('serviceWorker' in navigator) && ('PushManager' in window);
// Reject when browser not service worker supported
if (!isSwSupported) return;
// Reject when not signed in to Misskey
2018-05-26 23:49:09 -05:00
if (!this.store.getters.isSignedIn) return;
2017-11-20 16:06:36 -06:00
// When service worker activated
navigator.serviceWorker.ready.then(registration => {
this.swRegistration = registration;
// Options of pushManager.subscribe
// SEE: https://developer.mozilla.org/en-US/docs/Web/API/PushManager/subscribe#Parameters
2017-11-20 16:06:36 -06:00
const opts = {
// A boolean indicating that the returned push subscription
// will only be used for messages whose effect is made visible to the user.
userVisibleOnly: true,
// A public key your push server will use to send
// messages to client apps via a push server.
2019-03-05 18:24:16 -06:00
applicationServerKey: urlBase64ToUint8Array(swPublickey)
2017-11-20 16:06:36 -06:00
};
// Subscribe push notification
this.swRegistration.pushManager.subscribe(opts).then(subscription => {
function encode(buffer: ArrayBuffer) {
return btoa(String.fromCharCode.apply(null, new Uint8Array(buffer)));
}
// Register
this.api('sw/register', {
endpoint: subscription.endpoint,
auth: encode(subscription.getKey('auth')),
publickey: encode(subscription.getKey('p256dh'))
});
2017-11-22 18:52:45 -06:00
})
// When subscribe failed
.catch(async (err: Error) => {
// 通知が許可されていなかったとき
if (err.name == 'NotAllowedError') {
return;
}
2017-11-22 15:26:22 -06:00
// 違うapplicationServerKey (または gcm_sender_id)のサブスクリプションが
// 既に存在していることが原因でエラーになった可能性があるので、
// そのサブスクリプションを解除しておく
const subscription = await this.swRegistration.pushManager.getSubscription();
if (subscription) subscription.unsubscribe();
2017-11-20 12:40:09 -06:00
});
2017-11-20 16:06:36 -06:00
});
// The path of service worker script
const sw = `/sw.${version}.js`;
2017-11-20 16:06:36 -06:00
// Register service worker
navigator.serviceWorker.register(sw);
2017-11-20 12:40:09 -06:00
}
2017-11-15 12:06:52 -06:00
/**
* Misskey APIにリクエストします
* @param endpoint
* @param data
*/
@autobind
public api(endpoint: string, data: { [x: string]: any } = {}, token?): Promise<{ [x: string]: any }> {
if (++pending === 1) {
spinner = document.createElement('div');
spinner.setAttribute('id', 'wait');
document.body.appendChild(spinner);
2018-03-02 23:42:25 -06:00
}
2018-04-13 13:40:12 -05:00
const onFinally = () => {
if (--pending === 0) spinner.parentNode.removeChild(spinner);
2018-04-13 13:40:12 -05:00
};
const promise = new Promise((resolve, reject) => {
// Append a credential
if (this.store.getters.isSignedIn) (data as any).i = this.store.state.i.token;
if (token) (data as any).i = token;
// Send request
fetch(endpoint.indexOf('://') > -1 ? endpoint : `${apiUrl}/${endpoint}`, {
method: 'POST',
body: JSON.stringify(data),
credentials: 'omit',
cache: 'no-cache'
}).then(async (res) => {
const body = res.status === 204 ? null : await res.json();
2018-03-15 05:53:46 -05:00
if (res.status === 200) {
resolve(body);
} else if (res.status === 204) {
resolve();
} else {
reject(body.error);
}
}).catch(reject);
2018-03-02 23:42:25 -06:00
});
2018-04-13 13:40:12 -05:00
promise.then(onFinally, onFinally);
return promise;
2017-11-15 12:06:52 -06:00
}
}
/**
* Convert the URL safe base64 string to a Uint8Array
* @param base64String base64 string
*/
function urlBase64ToUint8Array(base64String: string): Uint8Array {
const padding = '='.repeat((4 - base64String.length % 4) % 4);
const base64 = (base64String + padding)
.replace(/-/g, '+')
.replace(/_/g, '/');
const rawData = window.atob(base64);
const outputArray = new Uint8Array(rawData.length);
for (let i = 0; i < rawData.length; ++i) {
outputArray[i] = rawData.charCodeAt(i);
}
return outputArray;
}