1
0
mirror of https://github.com/misskey-dev/misskey synced 2024-12-28 21:48:26 +09:00
misskey/src/client/app/mios.ts

580 lines
14 KiB
TypeScript
Raw Normal View History

2018-02-22 05:05:19 +09:00
import Vue from 'vue';
2017-11-16 03:06:52 +09:00
import { EventEmitter } from 'eventemitter3';
2018-03-15 19:53:46 +09:00
import * as uuid from 'uuid';
2018-02-25 00:18:09 +09:00
2018-04-29 21:41:48 +09:00
import initStore from './store';
import { apiUrl, version, lang } from './config';
2018-04-29 21:41:48 +09:00
import Progress from './common/scripts/loading';
import Connection from './common/scripts/streaming/stream';
import { HomeStreamManager } from './common/scripts/streaming/home';
import { DriveStreamManager } from './common/scripts/streaming/drive';
2018-06-09 04:14:26 +09:00
import { ServerStatsStreamManager } from './common/scripts/streaming/server-stats';
import { NotesStatsStreamManager } from './common/scripts/streaming/notes-stats';
2018-04-29 21:41:48 +09:00
import { MessagingIndexStreamManager } from './common/scripts/streaming/messaging-index';
2018-07-11 13:47:01 +09:00
import { ReversiStreamManager } from './common/scripts/streaming/games/reversi/reversi';
2017-11-16 03:06:52 +09:00
2018-04-29 22:04:51 +09:00
import Err from './common/views/components/connect-failed.vue';
2018-04-29 21:41:48 +09:00
import { LocalTimelineStreamManager } from './common/scripts/streaming/local-timeline';
2018-07-11 09:36:30 +09:00
import { HybridTimelineStreamManager } from './common/scripts/streaming/hybrid-timeline';
2018-04-29 21:41:48 +09:00
import { GlobalTimelineStreamManager } from './common/scripts/streaming/global-timeline';
2018-02-22 05:05:19 +09:00
2018-03-03 14:42:25 +09:00
//#region api requests
let spinner = null;
let pending = 0;
//#endregion
2018-02-21 02:53:34 +09:00
export type API = {
chooseDriveFile: (opts: {
title?: string;
currentFolder?: any;
multiple?: boolean;
}) => Promise<any>;
chooseDriveFolder: (opts: {
title?: string;
currentFolder?: any;
}) => Promise<any>;
dialog: (opts: {
title: string;
text: string;
2018-03-02 18:46:08 +09:00
actions?: Array<{
2018-02-21 02:53:34 +09:00
text: string;
id?: string;
}>;
}) => Promise<string>;
input: (opts: {
title: string;
placeholder?: string;
default?: string;
}) => Promise<string>;
2018-02-22 02:15:46 +09:00
post: (opts?: {
reply?: any;
2018-04-08 02:30:37 +09:00
renote?: any;
2018-02-22 02:15:46 +09:00
}) => void;
2018-02-21 02:53:34 +09:00
notify: (message: string) => void;
};
2017-11-16 03:06:52 +09:00
/**
* Misskey Operating System
*/
export default class MiOS extends EventEmitter {
/**
* Misskeyの /meta
*/
private meta: {
data: { [x: string]: any };
chachedAt: Date;
};
2018-08-19 21:07:18 +09:00
public get instanceName() {
return this.meta ? this.meta.data.name : 'Misskey';
}
2017-11-16 03:06:52 +09:00
private isMetaFetching = false;
2018-02-22 23:53:07 +09:00
public app: Vue;
public new(vm, props) {
2018-06-06 05:18:08 +09:00
const x = new vm({
2018-02-22 23:53:07 +09:00
parent: this.app,
propsData: props
}).$mount();
2018-06-06 05:18:08 +09:00
document.body.appendChild(x.$el);
return x;
2018-02-22 23:53:07 +09:00
}
2017-11-21 07:06:36 +09:00
/**
* Whether is debug mode
*/
public get debug() {
2018-05-21 02:13:39 +09:00
return this.store ? this.store.state.device.debug : false;
2018-03-04 18:50:30 +09:00
}
2018-04-29 17:17:15 +09:00
public store: ReturnType<typeof initStore>;
2018-02-21 02:53:34 +09:00
public apis: API;
2017-11-16 03:06:52 +09:00
/**
2017-11-17 01:24:44 +09:00
* A connection manager of home stream
2017-11-16 03:06:52 +09:00
*/
2017-11-17 01:24:44 +09:00
public stream: HomeStreamManager;
2017-11-16 03:06:52 +09:00
2018-02-09 18:28:06 +09:00
/**
* Connection managers
*/
public streams: {
localTimelineStream: LocalTimelineStreamManager;
2018-07-11 14:03:21 +09:00
hybridTimelineStream: HybridTimelineStreamManager;
globalTimelineStream: GlobalTimelineStreamManager;
2018-02-09 18:28:06 +09:00
driveStream: DriveStreamManager;
2018-06-09 04:14:26 +09:00
serverStatsStream: ServerStatsStreamManager;
notesStatsStream: NotesStatsStreamManager;
2018-02-09 18:28:06 +09:00
messagingIndexStream: MessagingIndexStreamManager;
2018-06-17 08:10:54 +09:00
reversiStream: ReversiStreamManager;
2018-02-10 10:52:26 +09:00
} = {
localTimelineStream: null,
2018-07-11 14:03:21 +09:00
hybridTimelineStream: null,
globalTimelineStream: null,
2018-02-10 10:52:26 +09:00
driveStream: null,
2018-06-09 04:14:26 +09:00
serverStatsStream: null,
notesStatsStream: null,
2018-03-07 17:48:32 +09:00
messagingIndexStream: null,
2018-06-17 08:10:54 +09:00
reversiStream: null
2018-02-09 18:28:06 +09:00
};
2017-11-21 03:40:09 +09:00
/**
* A registration of service worker
*/
private swRegistration: ServiceWorkerRegistration = null;
2017-11-21 10:01:00 +09:00
/**
* Whether should register ServiceWorker
*/
private shouldRegisterSw: boolean;
2018-02-11 22:04:08 +09:00
/**
*
*/
public windows = new WindowSystem();
2017-11-21 10:01:00 +09:00
/**
* MiOSインスタンスを作成します
* @param shouldRegisterSw ServiceWorkerを登録するかどうか
*/
constructor(shouldRegisterSw = false) {
2017-11-16 03:06:52 +09:00
super();
2017-11-21 10:01:00 +09:00
this.shouldRegisterSw = shouldRegisterSw;
2017-11-16 03:06:52 +09:00
//#region BIND
2017-11-21 07:06:36 +09:00
this.log = this.log.bind(this);
this.logInfo = this.logInfo.bind(this);
this.logWarn = this.logWarn.bind(this);
this.logError = this.logError.bind(this);
2017-11-16 03:06:52 +09:00
this.init = this.init.bind(this);
this.api = this.api.bind(this);
this.getMeta = this.getMeta.bind(this);
2017-11-21 07:06:36 +09:00
this.registerSw = this.registerSw.bind(this);
2017-11-16 03:06:52 +09:00
//#endregion
2018-02-09 18:28:06 +09:00
if (this.debug) {
(window as any).os = this;
}
}
2018-03-06 07:39:47 +09:00
private googleMapsIniting = false;
public getGoogleMaps() {
return new Promise((res, rej) => {
if ((window as any).google && (window as any).google.maps) {
res((window as any).google.maps);
} else {
this.once('init-google-maps', () => {
res((window as any).google.maps);
});
2018-03-06 07:39:47 +09:00
//#region load google maps api
if (!this.googleMapsIniting) {
this.googleMapsIniting = true;
(window as any).initGoogleMaps = () => {
this.emit('init-google-maps');
};
const head = document.getElementsByTagName('head')[0];
const script = document.createElement('script');
script.setAttribute('src', `https://maps.googleapis.com/maps/api/js?key=${googleMapsApiKey}&callback=initGoogleMaps`);
script.setAttribute('async', 'true');
script.setAttribute('defer', 'true');
head.appendChild(script);
}
//#endregion
}
});
2017-11-16 03:06:52 +09:00
}
2017-11-21 07:06:36 +09:00
public log(...args) {
if (!this.debug) return;
console.log.apply(null, args);
}
public logInfo(...args) {
if (!this.debug) return;
console.info.apply(null, args);
}
public logWarn(...args) {
if (!this.debug) return;
console.warn.apply(null, args);
}
public logError(...args) {
if (!this.debug) return;
console.error.apply(null, args);
}
2018-02-26 19:23:53 +09:00
public signout() {
2018-05-27 13:49:09 +09:00
this.store.dispatch('logout');
2018-02-26 19:23:53 +09:00
location.href = '/';
}
2017-11-16 03:06:52 +09:00
/**
* Initialize MiOS (boot)
* @param callback A function that call when initialized
*/
public async init(callback) {
2018-04-29 17:17:15 +09:00
this.store = initStore(this);
2018-03-15 19:53:46 +09:00
//#region Init stream managers
2018-06-09 04:14:26 +09:00
this.streams.serverStatsStream = new ServerStatsStreamManager(this);
this.streams.notesStatsStream = new NotesStatsStreamManager(this);
this.streams.localTimelineStream = new LocalTimelineStreamManager(this, this.store.state.i);
2018-03-15 19:53:46 +09:00
this.once('signedin', () => {
// Init home stream manager
2018-05-27 13:49:09 +09:00
this.stream = new HomeStreamManager(this, this.store.state.i);
2018-03-15 19:53:46 +09:00
// Init other stream manager
2018-07-11 14:03:21 +09:00
this.streams.hybridTimelineStream = new HybridTimelineStreamManager(this, this.store.state.i);
2018-05-27 13:49:09 +09:00
this.streams.globalTimelineStream = new GlobalTimelineStreamManager(this, this.store.state.i);
this.streams.driveStream = new DriveStreamManager(this, this.store.state.i);
this.streams.messagingIndexStream = new MessagingIndexStreamManager(this, this.store.state.i);
2018-06-17 08:10:54 +09:00
this.streams.reversiStream = new ReversiStreamManager(this, this.store.state.i);
2018-03-15 19:53:46 +09:00
});
//#endregion
2017-11-16 03:06:52 +09:00
// ユーザーをフェッチしてコールバックする
const fetchme = (token, cb) => {
let me = null;
// Return when not signed in
if (token == null) {
return done();
}
// Fetch user
2018-02-25 00:18:09 +09:00
fetch(`${apiUrl}/i`, {
2017-11-16 03:06:52 +09:00
method: 'POST',
body: JSON.stringify({
i: token
})
2017-11-17 01:24:44 +09:00
})
// When success
.then(res => {
2017-11-16 03:06:52 +09:00
// When failed to authenticate user
if (res.status !== 200) {
2018-02-26 19:23:53 +09:00
return this.signout();
2017-11-16 03:06:52 +09:00
}
2017-11-17 01:24:44 +09:00
// Parse response
2017-11-16 03:06:52 +09:00
res.json().then(i => {
me = i;
2018-04-08 03:58:11 +09:00
me.token = token;
2017-11-16 03:06:52 +09:00
done();
});
2017-11-17 01:24:44 +09:00
})
// When failure
.catch(() => {
2017-11-16 03:06:52 +09:00
// Render the error screen
2018-02-22 05:05:19 +09:00
document.body.innerHTML = '<div id="err"></div>';
new Vue({
render: createEl => createEl(Err)
}).$mount('#err');
2017-11-17 01:24:44 +09:00
2017-11-16 03:06:52 +09:00
Progress.done();
});
function done() {
if (cb) cb(me);
}
};
// フェッチが完了したとき
2018-05-27 13:49:09 +09:00
const fetched = () => {
2018-02-09 18:28:06 +09:00
this.emit('signedin');
2017-11-16 03:06:52 +09:00
// Finish init
callback();
2017-11-21 03:40:09 +09:00
2017-11-21 07:06:36 +09:00
// Init service worker
2017-11-21 10:01:00 +09:00
if (this.shouldRegisterSw) this.registerSw();
2017-11-16 03:06:52 +09:00
};
2017-11-21 07:06:36 +09:00
// キャッシュがあったとき
2018-05-27 13:49:09 +09:00
if (this.store.state.i != null) {
if (this.store.state.i.token == null) {
2018-04-08 04:44:59 +09:00
this.signout();
return;
}
2017-11-21 07:06:36 +09:00
// とりあえずキャッシュされたデータでお茶を濁して(?)おいて、
2018-05-27 13:49:09 +09:00
fetched();
2017-11-16 03:06:52 +09:00
// 後から新鮮なデータをフェッチ
2018-05-27 13:49:09 +09:00
fetchme(this.store.state.i.token, freshData => {
this.store.dispatch('mergeMe', freshData);
2017-11-16 03:06:52 +09:00
});
} else {
// Get token from cookie
const i = (document.cookie.match(/i=(!\w+)/) || [null, null])[1];
2018-04-29 17:17:15 +09:00
fetchme(i, me => {
if (me) {
2018-05-27 13:49:09 +09:00
this.store.dispatch('login', me);
fetched();
2018-04-29 17:17:15 +09:00
} else {
// Finish init
callback();
}
});
2017-11-16 03:06:52 +09:00
}
}
2017-11-21 07:06:36 +09:00
/**
* Register service worker
*/
private registerSw() {
// 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-27 13:49:09 +09:00
if (!this.store.getters.isSignedIn) return;
2017-11-21 07:06:36 +09:00
// When service worker activated
navigator.serviceWorker.ready.then(registration => {
this.log('[sw] ready: ', registration);
this.swRegistration = registration;
// Options of pushManager.subscribe
// SEE: https://developer.mozilla.org/en-US/docs/Web/API/PushManager/subscribe#Parameters
2017-11-21 07:06:36 +09: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.
applicationServerKey: urlBase64ToUint8Array(this.meta.data.swPublickey)
2017-11-21 07:06:36 +09:00
};
// Subscribe push notification
this.swRegistration.pushManager.subscribe(opts).then(subscription => {
this.log('[sw] Subscribe OK:', 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-23 09:52:45 +09:00
})
// When subscribe failed
.catch(async (err: Error) => {
2017-11-21 07:06:36 +09:00
this.logError('[sw] Subscribe Error:', err);
2017-11-23 06:26:22 +09:00
2017-11-23 09:52:45 +09:00
// 通知が許可されていなかったとき
if (err.name == 'NotAllowedError') {
this.logError('[sw] Subscribe failed due to notification not allowed');
return;
}
2017-11-23 06:26:22 +09:00
// 違うapplicationServerKey (または gcm_sender_id)のサブスクリプションが
// 既に存在していることが原因でエラーになった可能性があるので、
// そのサブスクリプションを解除しておく
const subscription = await this.swRegistration.pushManager.getSubscription();
if (subscription) subscription.unsubscribe();
2017-11-21 03:40:09 +09:00
});
2017-11-21 07:06:36 +09:00
});
// The path of service worker script
2018-05-21 02:13:39 +09:00
const sw = `/sw.${version}.${lang}.js`;
2017-11-21 07:06:36 +09:00
// Register service worker
navigator.serviceWorker.register(sw).then(registration => {
// 登録成功
this.logInfo('[sw] Registration successful with scope: ', registration.scope);
2017-11-21 03:40:09 +09:00
}).catch(err => {
2017-11-21 07:06:36 +09:00
// 登録失敗 :(
this.logError('[sw] Registration failed: ', err);
2017-11-21 03:40:09 +09:00
});
}
2018-03-15 19:53:46 +09:00
public requests = [];
2017-11-16 03:06:52 +09:00
/**
* Misskey APIにリクエストします
* @param endpoint
* @param data
*/
2018-03-03 14:42:25 +09:00
public api(endpoint: string, data: { [x: string]: any } = {}): Promise<{ [x: string]: any }> {
if (++pending === 1) {
spinner = document.createElement('div');
spinner.setAttribute('id', 'wait');
document.body.appendChild(spinner);
}
2018-04-14 03:40:12 +09:00
const onFinally = () => {
if (--pending === 0) spinner.parentNode.removeChild(spinner);
};
const promise = new Promise((resolve, reject) => {
2018-05-21 02:13:39 +09:00
const viaStream = this.stream && this.stream.hasConnection && this.store.state.device.apiViaStream;
2018-04-13 09:44:00 +09:00
if (viaStream) {
2018-03-03 14:42:25 +09:00
const stream = this.stream.borrow();
const id = Math.random().toString();
2018-03-03 14:42:25 +09:00
stream.once(`api-res:${id}`, res => {
2018-04-14 06:18:18 +09:00
if (res == null || Object.keys(res).length == 0) {
resolve(null);
} else if (res.res) {
resolve(res.res);
} else {
reject(res.e);
}
2018-03-03 14:42:25 +09:00
});
2018-03-03 14:42:25 +09:00
stream.send({
type: 'api',
id,
endpoint,
data
});
} else {
// Append a credential
2018-05-27 13:49:09 +09:00
if (this.store.getters.isSignedIn) (data as any).i = this.store.state.i.token;
2018-03-15 19:53:46 +09:00
const req = {
id: uuid(),
date: new Date(),
name: endpoint,
data,
res: null,
status: null
};
if (this.debug) {
this.requests.push(req);
}
2018-03-03 14:42:25 +09:00
// Send request
fetch(endpoint.indexOf('://') > -1 ? endpoint : `${apiUrl}/${endpoint}`, {
method: 'POST',
body: JSON.stringify(data),
credentials: endpoint === 'signin' ? 'include' : 'omit',
cache: 'no-cache'
2018-03-15 19:53:46 +09:00
}).then(async (res) => {
2018-03-16 06:02:18 +09:00
const body = res.status === 204 ? null : await res.json();
2018-03-15 19:53:46 +09:00
if (this.debug) {
req.status = res.status;
req.res = body;
}
2018-03-03 14:42:25 +09:00
if (res.status === 200) {
2018-03-15 19:53:46 +09:00
resolve(body);
2018-03-03 14:42:25 +09:00
} else if (res.status === 204) {
resolve();
} else {
2018-03-15 19:53:46 +09:00
reject(body.error);
2018-03-03 14:42:25 +09:00
}
}).catch(reject);
2018-04-12 06:18:55 +09:00
}
2018-03-03 14:42:25 +09:00
});
2018-04-14 03:40:12 +09:00
promise.then(onFinally, onFinally);
return promise;
2017-11-16 03:06:52 +09:00
}
/**
* Misskeyのメタ情報を取得します
* @param force
*/
public getMeta(force = false) {
return new Promise<{ [x: string]: any }>(async (res, rej) => {
if (this.isMetaFetching) {
this.once('_meta_fetched_', () => {
res(this.meta.data);
});
return;
}
const expire = 1000 * 60; // 1min
// forceが有効, meta情報を保持していない or 期限切れ
if (force || this.meta == null || Date.now() - this.meta.chachedAt.getTime() > expire) {
this.isMetaFetching = true;
const meta = await this.api('meta');
this.meta = {
data: meta,
chachedAt: new Date()
};
this.isMetaFetching = false;
this.emit('_meta_fetched_');
res(meta);
} else {
res(this.meta.data);
}
});
}
2018-03-15 19:53:46 +09:00
public connections: Connection[] = [];
public registerStreamConnection(connection: Connection) {
this.connections.push(connection);
}
public unregisterStreamConnection(connection: Connection) {
this.connections = this.connections.filter(c => c != connection);
}
2017-11-16 03:06:52 +09:00
}
2018-03-15 19:53:46 +09:00
class WindowSystem extends EventEmitter {
public windows = new Set();
2018-02-11 22:04:08 +09:00
public add(window) {
this.windows.add(window);
2018-03-15 19:53:46 +09:00
this.emit('added', window);
2018-02-11 22:04:08 +09:00
}
public remove(window) {
this.windows.delete(window);
2018-03-15 19:53:46 +09:00
this.emit('removed', window);
2018-02-11 22:04:08 +09:00
}
public getAll() {
return this.windows;
}
}
/**
* 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;
}