2017-11-15 10:06:52 -08:00
|
|
|
import { EventEmitter } from 'eventemitter3';
|
|
|
|
import * as riot from 'riot';
|
|
|
|
import signout from './scripts/signout';
|
|
|
|
import Progress from './scripts/loading';
|
2017-11-16 08:24:44 -08:00
|
|
|
import HomeStreamManager from './scripts/streaming/home-stream-manager';
|
2017-11-15 10:06:52 -08:00
|
|
|
import CONFIG from './scripts/config';
|
|
|
|
import api from './scripts/api';
|
|
|
|
|
2017-11-20 12:09:45 -08:00
|
|
|
declare var VERSION: string;
|
|
|
|
declare var LANG: string;
|
|
|
|
|
2017-11-15 10:06:52 -08:00
|
|
|
/**
|
|
|
|
* Misskey Operating System
|
|
|
|
*/
|
|
|
|
export default class MiOS extends EventEmitter {
|
|
|
|
/**
|
|
|
|
* Misskeyの /meta で取得できるメタ情報
|
|
|
|
*/
|
|
|
|
private meta: {
|
|
|
|
data: { [x: string]: any };
|
|
|
|
chachedAt: Date;
|
|
|
|
};
|
|
|
|
|
|
|
|
private isMetaFetching = false;
|
|
|
|
|
|
|
|
/**
|
|
|
|
* A signing user
|
|
|
|
*/
|
2017-11-15 16:00:24 -08:00
|
|
|
public i: { [x: string]: any };
|
2017-11-15 10:06:52 -08:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Whether signed in
|
|
|
|
*/
|
|
|
|
public get isSignedin() {
|
|
|
|
return this.i != null;
|
|
|
|
}
|
|
|
|
|
2017-11-20 14:06:36 -08:00
|
|
|
/**
|
|
|
|
* Whether is debug mode
|
|
|
|
*/
|
|
|
|
public get debug() {
|
|
|
|
return localStorage.getItem('debug') == 'true';
|
|
|
|
}
|
|
|
|
|
2017-11-15 10:06:52 -08:00
|
|
|
/**
|
2017-11-16 08:24:44 -08:00
|
|
|
* A connection manager of home stream
|
2017-11-15 10:06:52 -08:00
|
|
|
*/
|
2017-11-16 08:24:44 -08:00
|
|
|
public stream: HomeStreamManager;
|
2017-11-15 10:06:52 -08:00
|
|
|
|
2017-11-20 10:40:09 -08:00
|
|
|
/**
|
|
|
|
* A registration of service worker
|
|
|
|
*/
|
|
|
|
private swRegistration: ServiceWorkerRegistration = null;
|
|
|
|
|
2017-11-20 17:01:00 -08:00
|
|
|
/**
|
|
|
|
* Whether should register ServiceWorker
|
|
|
|
*/
|
|
|
|
private shouldRegisterSw: boolean;
|
|
|
|
|
|
|
|
/**
|
|
|
|
* MiOSインスタンスを作成します
|
|
|
|
* @param shouldRegisterSw ServiceWorkerを登録するかどうか
|
|
|
|
*/
|
|
|
|
constructor(shouldRegisterSw = false) {
|
2017-11-15 10:06:52 -08:00
|
|
|
super();
|
|
|
|
|
2017-11-20 17:01:00 -08:00
|
|
|
this.shouldRegisterSw = shouldRegisterSw;
|
|
|
|
|
2017-11-15 10:06:52 -08:00
|
|
|
//#region BIND
|
2017-11-20 14:06:36 -08: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-15 10:06:52 -08:00
|
|
|
this.init = this.init.bind(this);
|
|
|
|
this.api = this.api.bind(this);
|
|
|
|
this.getMeta = this.getMeta.bind(this);
|
2017-11-20 14:06:36 -08:00
|
|
|
this.registerSw = this.registerSw.bind(this);
|
2017-11-15 10:06:52 -08:00
|
|
|
//#endregion
|
|
|
|
}
|
|
|
|
|
2017-11-20 14:06:36 -08: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);
|
|
|
|
}
|
|
|
|
|
2017-11-15 10:06:52 -08:00
|
|
|
/**
|
|
|
|
* Initialize MiOS (boot)
|
|
|
|
* @param callback A function that call when initialized
|
|
|
|
*/
|
|
|
|
public async init(callback) {
|
|
|
|
// ユーザーをフェッチしてコールバックする
|
|
|
|
const fetchme = (token, cb) => {
|
|
|
|
let me = null;
|
|
|
|
|
|
|
|
// Return when not signed in
|
|
|
|
if (token == null) {
|
|
|
|
return done();
|
|
|
|
}
|
|
|
|
|
|
|
|
// Fetch user
|
|
|
|
fetch(`${CONFIG.apiUrl}/i`, {
|
|
|
|
method: 'POST',
|
|
|
|
body: JSON.stringify({
|
|
|
|
i: token
|
|
|
|
})
|
2017-11-16 08:24:44 -08:00
|
|
|
})
|
|
|
|
// When success
|
|
|
|
.then(res => {
|
2017-11-15 10:06:52 -08:00
|
|
|
// When failed to authenticate user
|
|
|
|
if (res.status !== 200) {
|
|
|
|
return signout();
|
|
|
|
}
|
|
|
|
|
2017-11-16 08:24:44 -08:00
|
|
|
// Parse response
|
2017-11-15 10:06:52 -08:00
|
|
|
res.json().then(i => {
|
|
|
|
me = i;
|
|
|
|
me.token = token;
|
|
|
|
done();
|
|
|
|
});
|
2017-11-16 08:24:44 -08:00
|
|
|
})
|
|
|
|
// When failure
|
|
|
|
.catch(() => {
|
2017-11-15 10:06:52 -08:00
|
|
|
// Render the error screen
|
|
|
|
document.body.innerHTML = '<mk-error />';
|
|
|
|
riot.mount('*');
|
2017-11-16 08:24:44 -08:00
|
|
|
|
2017-11-15 10:06:52 -08:00
|
|
|
Progress.done();
|
|
|
|
});
|
|
|
|
|
|
|
|
function done() {
|
|
|
|
if (cb) cb(me);
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
// フェッチが完了したとき
|
|
|
|
const fetched = me => {
|
|
|
|
if (me) {
|
|
|
|
riot.observable(me);
|
|
|
|
|
|
|
|
// この me オブジェクトを更新するメソッド
|
|
|
|
me.update = data => {
|
|
|
|
if (data) Object.assign(me, data);
|
|
|
|
me.trigger('updated');
|
|
|
|
};
|
|
|
|
|
|
|
|
// ローカルストレージにキャッシュ
|
|
|
|
localStorage.setItem('me', JSON.stringify(me));
|
|
|
|
|
2017-11-16 08:24:44 -08:00
|
|
|
// 自分の情報が更新されたとき
|
2017-11-15 10:06:52 -08:00
|
|
|
me.on('updated', () => {
|
|
|
|
// キャッシュ更新
|
|
|
|
localStorage.setItem('me', JSON.stringify(me));
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
this.i = me;
|
|
|
|
|
2017-11-16 08:24:44 -08:00
|
|
|
// Init home stream manager
|
|
|
|
this.stream = this.isSignedin
|
|
|
|
? new HomeStreamManager(this.i)
|
|
|
|
: null;
|
2017-11-15 10:06:52 -08:00
|
|
|
|
|
|
|
// Finish init
|
|
|
|
callback();
|
2017-11-20 10:40:09 -08:00
|
|
|
|
2017-11-20 14:06:36 -08:00
|
|
|
//#region Post
|
|
|
|
|
|
|
|
// Init service worker
|
2017-11-20 17:01:00 -08:00
|
|
|
if (this.shouldRegisterSw) this.registerSw();
|
2017-11-20 14:06:36 -08:00
|
|
|
|
2017-11-20 10:40:09 -08:00
|
|
|
//#endregion
|
2017-11-15 10:06:52 -08:00
|
|
|
};
|
|
|
|
|
|
|
|
// Get cached account data
|
|
|
|
const cachedMe = JSON.parse(localStorage.getItem('me'));
|
|
|
|
|
2017-11-20 14:06:36 -08:00
|
|
|
// キャッシュがあったとき
|
2017-11-15 10:06:52 -08:00
|
|
|
if (cachedMe) {
|
2017-11-20 14:06:36 -08:00
|
|
|
// とりあえずキャッシュされたデータでお茶を濁して(?)おいて、
|
2017-11-15 10:06:52 -08:00
|
|
|
fetched(cachedMe);
|
|
|
|
|
|
|
|
// 後から新鮮なデータをフェッチ
|
|
|
|
fetchme(cachedMe.token, freshData => {
|
|
|
|
Object.assign(cachedMe, freshData);
|
|
|
|
cachedMe.trigger('updated');
|
2017-11-20 19:40:48 -08:00
|
|
|
cachedMe.trigger('refreshed');
|
2017-11-15 10:06:52 -08:00
|
|
|
});
|
|
|
|
} else {
|
|
|
|
// Get token from cookie
|
|
|
|
const i = (document.cookie.match(/i=(!\w+)/) || [null, null])[1];
|
|
|
|
|
|
|
|
fetchme(i, fetched);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-11-20 14:06:36 -08: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
|
|
|
|
if (!this.isSignedin) return;
|
|
|
|
|
|
|
|
// When service worker activated
|
|
|
|
navigator.serviceWorker.ready.then(registration => {
|
|
|
|
this.log('[sw] ready: ', registration);
|
|
|
|
|
|
|
|
this.swRegistration = registration;
|
|
|
|
|
|
|
|
// Options of pushManager.subscribe
|
|
|
|
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
|
|
|
|
};
|
|
|
|
|
|
|
|
// 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'))
|
|
|
|
});
|
|
|
|
}).then(() => {
|
|
|
|
this.logInfo('[sw] Server Stored Subscription.');
|
|
|
|
}).catch(err => {
|
|
|
|
this.logError('[sw] Subscribe Error:', err);
|
2017-11-20 10:40:09 -08:00
|
|
|
});
|
2017-11-20 14:06:36 -08:00
|
|
|
});
|
|
|
|
|
|
|
|
// The path of service worker script
|
|
|
|
const sw = `/sw.${VERSION}.${LANG}.js`;
|
|
|
|
|
|
|
|
// Register service worker
|
|
|
|
navigator.serviceWorker.register(sw).then(registration => {
|
|
|
|
// 登録成功
|
|
|
|
this.logInfo('[sw] Registration successful with scope: ', registration.scope);
|
2017-11-20 10:40:09 -08:00
|
|
|
}).catch(err => {
|
2017-11-20 14:06:36 -08:00
|
|
|
// 登録失敗 :(
|
|
|
|
this.logError('[sw] Registration failed: ', err);
|
2017-11-20 10:40:09 -08:00
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2017-11-15 10:06:52 -08:00
|
|
|
/**
|
|
|
|
* Misskey APIにリクエストします
|
|
|
|
* @param endpoint エンドポイント名
|
|
|
|
* @param data パラメータ
|
|
|
|
*/
|
|
|
|
public api(endpoint: string, data?: { [x: string]: any }) {
|
|
|
|
return api(this.i, endpoint, data);
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* 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);
|
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|