Merge remote-tracking branch 'refs/remotes/origin/master' into vue-#972

This commit is contained in:
syuilo 2018-02-05 03:59:29 +09:00
commit dbd3cdb308
231 changed files with 5512 additions and 2710 deletions

View File

@ -1,6 +1,9 @@
# travis file # travis file
# https://docs.travis-ci.com/user/customizing-the-build # https://docs.travis-ci.com/user/customizing-the-build
notifications:
email: false
branches: branches:
except: except:
- release - release

View File

@ -2,6 +2,113 @@ ChangeLog (Release Notes)
========================= =========================
主に notable な changes を書いていきます 主に notable な changes を書いていきます
3493 (2018/01/01)
-----------------
* なんか
3460 (2017/12/23)
-----------------
* 検索で複数のユーザーを指定できるように
* 検索でユーザーを除外できるように
* など
3451 (2017/12/22)
-----------------
* ミュート機能
3430 (2017/12/21)
-----------------
* oops
3428 (2017/12/21)
-----------------
* バグ修正
3426 (2017/12/21)
-----------------
* 検索にpoll追加
3424 (2017/12/21)
-----------------
* 検索にrepost追加
* など
3422 (2017/12/21)
-----------------
* 検索にfollow追加 #1023
3420 (2017/12/21)
-----------------
* 検索機能を大幅に強化
3415 (2017/12/19)
-----------------
* デザインの調整
3404 (2017/12/17)
-----------------
* なんか
3400 (2017/12/17)
-----------------
* なんか
3392 (2017/12/17)
-----------------
* ドキュメントなど
3390 (2017/12/16)
-----------------
* ドキュメントなど
3347 (2017/12/11)
-----------------
* バグ修正
3342 (2017/12/11)
-----------------
* なんか
3339 (2017/12/11)
-----------------
* なんか
3334 (2017/12/10)
-----------------
* いい感じにした
3322 (2017/12/10)
-----------------
* :art:
3320 (2017/12/10)
-----------------
* なんか
3310 (2017/12/09)
-----------------
* i18nなど
3308 (2017/12/09)
-----------------
* :art:
3294 (2017/12/09)
-----------------
* バグ修正
3292 (2017/12/09)
-----------------
* ユーザビリティの向上
3281 (2017/12/08)
-----------------
* 二段階認証の実装 (#967)
3278 (2017/12/08)
-----------------
* :v:
3272 (2017/12/08) 3272 (2017/12/08)
----------------- -----------------
* Fix bug * Fix bug

View File

@ -1,6 +1,6 @@
The MIT License (MIT) The MIT License (MIT)
Copyright (c) 2014-2017 syuilo Copyright (c) 2014-2018 syuilo
Permission is hereby granted, free of charge, to any person obtaining a copy Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal of this software and associated documentation files (the "Software"), to deal

View File

@ -16,7 +16,7 @@ Key features
---------------------------------------------------------------- ----------------------------------------------------------------
* Automatically updated timeline * Automatically updated timeline
* Private messages * Private messages
* Free 1GB storage for each all users * Two-Factor Authentication support
* ServiceWorker support * ServiceWorker support
* Web API for third-party applications * Web API for third-party applications
* No ads * No ads

View File

@ -7,7 +7,7 @@ Make sure **mongodb-tools** installed.
In your shell: In your shell:
``` shell ``` shell
$ mongodump --archive=db-backup $ mongodump --archive=db-backup -u <YourUserName> -p <YourPassword>
``` ```
For details, plese see [mongodump docs](https://docs.mongodb.com/manual/reference/program/mongodump/). For details, plese see [mongodump docs](https://docs.mongodb.com/manual/reference/program/mongodump/).

View File

@ -49,4 +49,12 @@ sw:
# VAPIDの秘密鍵 # VAPIDの秘密鍵
private_key: private_key:
# Twitterインテグレーションの設定(利用しない場合は省略可能)
twitter:
# インテグレーション用アプリのコンシューマーキー
consumer_key:
# インテグレーション用アプリのコンシューマーシークレット
consumer_secret:
``` ```

View File

@ -24,7 +24,7 @@ Note that Misskey uses following subdomains:
* **api**.*{primary domain}* * **api**.*{primary domain}*
* **auth**.*{primary domain}* * **auth**.*{primary domain}*
* **about**.*{primary domain}* * **docs**.*{primary domain}*
* **ch**.*{primary domain}* * **ch**.*{primary domain}*
* **stats**.*{primary domain}* * **stats**.*{primary domain}*
* **status**.*{primary domain}* * **status**.*{primary domain}*
@ -53,7 +53,7 @@ Please install and setup these softwares:
* *Node.js* and *npm* * *Node.js* and *npm*
* **[MongoDB](https://www.mongodb.com/)** * **[MongoDB](https://www.mongodb.com/)**
* **[Redis](https://redis.io/)** * **[Redis](https://redis.io/)**
* **[GraphicsMagick](http://www.graphicsmagick.org/)** * **[ImageMagick](http://www.imagemagick.org/script/index.php)**
##### Optional ##### Optional
* [Elasticsearch](https://www.elastic.co/) - used to provide searching feature instead of MongoDB * [Elasticsearch](https://www.elastic.co/) - used to provide searching feature instead of MongoDB

View File

@ -25,7 +25,7 @@ Misskeyは以下のサブドメインを使います:
* **api**.*{primary domain}* * **api**.*{primary domain}*
* **auth**.*{primary domain}* * **auth**.*{primary domain}*
* **about**.*{primary domain}* * **docs**.*{primary domain}*
* **ch**.*{primary domain}* * **ch**.*{primary domain}*
* **stats**.*{primary domain}* * **stats**.*{primary domain}*
* **status**.*{primary domain}* * **status**.*{primary domain}*
@ -54,7 +54,7 @@ web-push generate-vapid-keys
* *Node.js* と *npm* * *Node.js* と *npm*
* **[MongoDB](https://www.mongodb.com/)** * **[MongoDB](https://www.mongodb.com/)**
* **[Redis](https://redis.io/)** * **[Redis](https://redis.io/)**
* **[GraphicsMagick](http://www.graphicsmagick.org/)** * **[ImageMagick](http://www.imagemagick.org/script/index.php)**
##### オプション ##### オプション
* [Elasticsearch](https://www.elastic.co/) - 検索機能を向上させるために用います。 * [Elasticsearch](https://www.elastic.co/) - 検索機能を向上させるために用います。

View File

@ -3,12 +3,12 @@
*/ */
import * as childProcess from 'child_process'; import * as childProcess from 'child_process';
import * as fs from 'fs';
import * as Path from 'path'; import * as Path from 'path';
import * as gulp from 'gulp'; import * as gulp from 'gulp';
import * as gutil from 'gulp-util'; import * as gutil from 'gulp-util';
import * as ts from 'gulp-typescript'; import * as ts from 'gulp-typescript';
import tslint from 'gulp-tslint'; import tslint from 'gulp-tslint';
import * as es from 'event-stream';
import cssnano = require('gulp-cssnano'); import cssnano = require('gulp-cssnano');
import * as uglifyComposer from 'gulp-uglify/composer'; import * as uglifyComposer from 'gulp-uglify/composer';
import pug = require('gulp-pug'); import pug = require('gulp-pug');
@ -20,17 +20,10 @@ import * as mocha from 'gulp-mocha';
import * as replace from 'gulp-replace'; import * as replace from 'gulp-replace';
import * as htmlmin from 'gulp-htmlmin'; import * as htmlmin from 'gulp-htmlmin';
const uglifyes = require('uglify-es'); const uglifyes = require('uglify-es');
import * as fontawesome from '@fortawesome/fontawesome';
import * as regular from '@fortawesome/fontawesome-free-regular';
import * as solid from '@fortawesome/fontawesome-free-solid';
import * as brands from '@fortawesome/fontawesome-free-brands';
// Add icons
fontawesome.library.add(regular);
fontawesome.library.add(solid);
fontawesome.library.add(brands);
import { fa } from './src/common/build/fa';
import version from './src/version'; import version from './src/version';
import config from './src/conf';
const uglify = uglifyComposer(uglifyes, console); const uglify = uglifyComposer(uglifyes, console);
@ -45,11 +38,14 @@ if (isDebug) {
const constants = require('./src/const.json'); const constants = require('./src/const.json');
require('./src/web/docs/gulpfile.ts');
gulp.task('build', [ gulp.task('build', [
'build:js', 'build:js',
'build:ts', 'build:ts',
'build:copy', 'build:copy',
'build:client' 'build:client',
'doc'
]); ]);
gulp.task('rebuild', ['clean', 'build']); gulp.task('rebuild', ['clean', 'build']);
@ -69,16 +65,10 @@ gulp.task('build:ts', () => {
}); });
gulp.task('build:copy', () => gulp.task('build:copy', () =>
es.merge( gulp.src([
gulp.src([ './src/**/assets/**/*',
'./src/**/assets/**/*', '!./src/web/app/**/assets/**/*'
'!./src/web/app/**/assets/**/*' ]).pipe(gulp.dest('./built/'))
]).pipe(gulp.dest('./built/')) as any,
gulp.src([
'./src/web/about/**/*',
'!./src/web/about/**/*.pug'
]).pipe(gulp.dest('./built/web/about/')) as any
)
); );
gulp.task('test', ['lint', 'mocha']); gulp.task('test', ['lint', 'mocha']);
@ -141,6 +131,7 @@ gulp.task('webpack', done => {
gulp.task('build:client:script', () => gulp.task('build:client:script', () =>
gulp.src(['./src/web/app/boot.js', './src/web/app/safe.js']) gulp.src(['./src/web/app/boot.js', './src/web/app/safe.js'])
.pipe(replace('VERSION', JSON.stringify(version))) .pipe(replace('VERSION', JSON.stringify(version)))
.pipe(replace('API', JSON.stringify(config.api_url)))
.pipe(isProduction ? uglify({ .pipe(isProduction ? uglify({
toplevel: true toplevel: true
} as any) : gutil.noop()) } as any) : gutil.noop())
@ -180,7 +171,9 @@ gulp.task('build:client:pug', [
.pipe(pug({ .pipe(pug({
locals: { locals: {
themeColor: constants.themeColor, themeColor: constants.themeColor,
facss: fontawesome.dom.css() facss: fa.dom.css(),
//hljscss: fs.readFileSync('./node_modules/highlight.js/styles/default.css', 'utf8')
hljscss: fs.readFileSync('./src/web/assets/code-highlight.css', 'utf8')
} }
})) }))
.pipe(htmlmin({ .pipe(htmlmin({

View File

@ -137,6 +137,7 @@ common:
mk-signin: mk-signin:
username: "Username" username: "Username"
password: "Password" password: "Password"
token: "Token"
signing-in: "Signing in..." signing-in: "Signing in..."
signin: "Sign in" signin: "Sign in"
@ -182,6 +183,24 @@ common:
mk-uploader: mk-uploader:
waiting: "Waiting" waiting: "Waiting"
docs:
edit-this-page-on-github: "Caught a mistake or want to contribute to the documentation? "
edit-this-page-on-github-link: "Edit this page on Github!"
api:
entities:
properties: "Properties"
endpoints:
params: "Parameters"
res: "Response"
props:
name: "Name"
type: "Type"
optional: "Optional"
description: "Description"
yes: "Yes"
no: "No"
ch: ch:
tags: tags:
mk-index: mk-index:
@ -198,7 +217,11 @@ ch:
desktop: desktop:
tags: tags:
mk-api-info: mk-api-info:
regenerate-token: "Please enter the password" intro: "APIを利用するには、上記のトークンを「i」というキーでパラメータに付加してリクエストします。"
caution: "アカウントを不正利用される可能性があるため、このトークンは第三者に教えないでください(アプリなどにも入力しないでください)。"
regeneration-of-token: "万が一このトークンが漏れたりその可能性がある場合はトークンを再生成できます。"
regenerate-token: "Regenerate the token"
enter-password: "Please enter the password"
mk-drive-browser-base-contextmenu: mk-drive-browser-base-contextmenu:
create-folder: "Create a folder" create-folder: "Create a folder"
@ -287,6 +310,15 @@ desktop:
mk-ui-header-notifications: mk-ui-header-notifications:
title: "Notifications" title: "Notifications"
mk-profile-setting:
avatar: "Avatar"
choice-avatar: "Choice an image"
name: "Name"
location: "Location"
description: "Description"
birthday: "Birthday"
save: "Update profile"
mk-password-setting: mk-password-setting:
reset: "Change your password" reset: "Change your password"
enter-current-password: "Enter the current password" enter-current-password: "Enter the current password"
@ -295,6 +327,28 @@ desktop:
not-match: "New password not matched" not-match: "New password not matched"
changed: "Password updated successfully" changed: "Password updated successfully"
mk-2fa-setting:
intro: "If you set up 2-step verification, you will need not only a password at sign-in but also a pre-registered physical device (such as your smartphone), which will improve security. "
detail: "See details..."
url: "https://www.google.com/landing/2step/"
caution: "As a caveat, security improves, but you can not sign in to Misskey if you lose a registered device, etc."
register: "Register a device"
already-registered: "The setting has already been completed."
unregister: "Disable"
unregistered: "Two-step authentication has been disabled."
enter-password: "Enter the password"
authenticator: "First, you need install Google Authenticator to your device:"
howtoinstall: "How to install"
scan: "Next, please scan displayed QR code:"
done: "Please enter the token displaying in your device:"
submit: "Submit"
success: "Setup completed successfully!"
failed: "Failed to setup. please ensure that the token is correct."
info: "From the next sign in, enter the token that is displayed on the device in addition to the password."
mk-mute-setting:
no-users: "No muted users"
mk-post-form: mk-post-form:
post-placeholder: "What's happening?" post-placeholder: "What's happening?"
reply-placeholder: "Reply to this post..." reply-placeholder: "Reply to this post..."
@ -327,7 +381,14 @@ desktop:
next: "Next post" next: "Next post"
mk-settings: mk-settings:
profile: "Profile"
mute: "Mute"
drive: "Drive"
security: "Security"
password: "Password" password: "Password"
2fa: "Two-factor authentication"
other: "Other"
license: "License"
mk-timeline-post: mk-timeline-post:
reposted-by: "Reposted by {}" reposted-by: "Reposted by {}"
@ -416,6 +477,11 @@ desktop:
mk-user: mk-user:
last-used-at: "Last used at" last-used-at: "Last used at"
follows-you: "Follows you"
mute: "Mute"
muted: "Muting"
unmute: "Unmute"
photos: photos:
title: "Photos" title: "Photos"
loading: "Loading" loading: "Loading"
@ -441,6 +507,7 @@ mobile:
rename: "Rename" rename: "Rename"
move: "Move" move: "Move"
hash: "Hash (md5)" hash: "Hash (md5)"
exif: "EXIF"
mk-entrance-signin: mk-entrance-signin:
signup: "Sign up" signup: "Sign up"
@ -490,7 +557,6 @@ mobile:
applications: "Applications" applications: "Applications"
twitter-integration: "Twitter integration" twitter-integration: "Twitter integration"
signin-history: "Sign in history" signin-history: "Sign in history"
api: "API"
link: "MisskeyLink" link: "MisskeyLink"
settings: "Settings" settings: "Settings"
signout: "Sign out" signout: "Sign out"
@ -554,7 +620,6 @@ mobile:
submit: "Post" submit: "Post"
reply-placeholder: "Reply to this post..." reply-placeholder: "Reply to this post..."
post-placeholder: "What's happening?" post-placeholder: "What's happening?"
attach-media-from-local: "Attach media from your device"
mk-search-posts: mk-search-posts:
empty: "There is no post related to the 「{}」" empty: "There is no post related to the 「{}」"

View File

@ -10,12 +10,12 @@ const loadLang = lang => yaml.safeLoad(
const native = loadLang('ja'); const native = loadLang('ja');
const langs = Object.entries({ const langs = {
'en': loadLang('en'), 'en': loadLang('en'),
'ja': native 'ja': native
}); };
langs.map(([, locale]) => { Object.entries(langs).map(([, locale]) => {
// Extend native language (Japanese) // Extend native language (Japanese)
locale = Object.assign({}, native, locale); locale = Object.assign({}, native, locale);
}); });

View File

@ -137,6 +137,7 @@ common:
mk-signin: mk-signin:
username: "ユーザー名" username: "ユーザー名"
password: "パスワード" password: "パスワード"
token: "トークン"
signing-in: "やってます..." signing-in: "やってます..."
signin: "サインイン" signin: "サインイン"
@ -182,6 +183,24 @@ common:
mk-uploader: mk-uploader:
waiting: "待機中" waiting: "待機中"
docs:
edit-this-page-on-github: "間違いや改善点を見つけましたか?"
edit-this-page-on-github-link: "このページをGitHubで編集"
api:
entities:
properties: "プロパティ"
endpoints:
params: "パラメータ"
res: "レスポンス"
props:
name: "名前"
type: "型"
optional: "オプション"
description: "説明"
yes: "はい"
no: "いいえ"
ch: ch:
tags: tags:
mk-index: mk-index:
@ -198,7 +217,11 @@ ch:
desktop: desktop:
tags: tags:
mk-api-info: mk-api-info:
regenerate-token: "パスワードを入力してください" intro: "APIを利用するには、上記のトークンを「i」というキーでパラメータに付加してリクエストします。"
caution: "アカウントを不正利用される可能性があるため、このトークンは第三者に教えないでください(アプリなどにも入力しないでください)。"
regeneration-of-token: "万が一このトークンが漏れたりその可能性がある場合はトークンを再生成できます。"
regenerate-token: "トークンを再生成"
enter-password: "パスワードを入力してください"
mk-drive-browser-base-contextmenu: mk-drive-browser-base-contextmenu:
create-folder: "フォルダーを作成" create-folder: "フォルダーを作成"
@ -287,6 +310,15 @@ desktop:
mk-ui-header-notifications: mk-ui-header-notifications:
title: "通知" title: "通知"
mk-profile-setting:
avatar: "アバター"
choice-avatar: "画像を選択"
name: "名前"
location: "場所"
description: "自己紹介"
birthday: "誕生日"
save: "保存"
mk-password-setting: mk-password-setting:
reset: "パスワードを変更する" reset: "パスワードを変更する"
enter-current-password: "現在のパスワードを入力してください" enter-current-password: "現在のパスワードを入力してください"
@ -295,6 +327,28 @@ desktop:
not-match: "新しいパスワードが一致しません" not-match: "新しいパスワードが一致しません"
changed: "パスワードを変更しました" changed: "パスワードを変更しました"
mk-2fa-setting:
intro: "二段階認証を設定すると、サインイン時にパスワードだけでなく、予め登録しておいた物理的なデバイス(例えばあなたのスマートフォンなど)も必要になり、よりセキュリティが向上します。"
detail: "詳細..."
url: "https://www.google.co.jp/intl/ja/landing/2step/"
caution: "登録したデバイスを紛失するなどした場合、Misskeyにサインインできなくなりますのでご注意ください。"
register: "デバイスを登録する"
already-registered: "既に設定は完了しています。"
unregister: "設定を解除"
unregistered: "二段階認証が無効になりました。"
enter-password: "パスワードを入力してください"
authenticator: "まず、Google Authenticatorをお使いのデバイスにインストールします:"
howtoinstall: "インストール方法はこちら"
scan: "次に、表示されているQRコードをスキャンします:"
done: "お使いのデバイスに表示されているトークンを入力して完了します:"
submit: "完了"
success: "設定が完了しました!"
failed: "設定に失敗しました。トークンに誤りがないかご確認ください。"
info: "次回サインインからは、同様にパスワードに加えてデバイスに表示されているトークンを入力します。"
mk-mute-setting:
no-users: "ミュートしているユーザーはいません"
mk-post-form: mk-post-form:
post-placeholder: "いまどうしてる?" post-placeholder: "いまどうしてる?"
reply-placeholder: "この投稿への返信..." reply-placeholder: "この投稿への返信..."
@ -327,7 +381,14 @@ desktop:
next: "次の投稿" next: "次の投稿"
mk-settings: mk-settings:
profile: "プロフィール"
mute: "ミュート"
drive: "ドライブ"
security: "セキュリティ"
password: "パスワード" password: "パスワード"
2fa: "二段階認証"
other: "その他"
license: "ライセンス"
mk-timeline-post: mk-timeline-post:
reposted-by: "{}がRepost" reposted-by: "{}がRepost"
@ -416,6 +477,11 @@ desktop:
mk-user: mk-user:
last-used-at: "最終アクセス" last-used-at: "最終アクセス"
follows-you: "フォローされています"
mute: "ミュートする"
muted: "ミュートしています"
unmute: "ミュート解除"
photos: photos:
title: "フォト" title: "フォト"
loading: "読み込み中" loading: "読み込み中"
@ -441,6 +507,7 @@ mobile:
rename: "名前を変更" rename: "名前を変更"
move: "移動" move: "移動"
hash: "ハッシュ (md5)" hash: "ハッシュ (md5)"
exif: "EXIF"
mk-entrance-signin: mk-entrance-signin:
signup: "新規登録" signup: "新規登録"
@ -489,8 +556,7 @@ mobile:
profile: "プロフィール" profile: "プロフィール"
applications: "アプリケーション" applications: "アプリケーション"
twitter-integration: "Twitter連携" twitter-integration: "Twitter連携"
signin-history: "ログイン履歴" signin-history: "サインイン履歴"
api: "API"
link: "Misskeyリンク" link: "Misskeyリンク"
settings: "設定" settings: "設定"
signout: "サインアウト" signout: "サインアウト"
@ -554,7 +620,6 @@ mobile:
submit: "投稿" submit: "投稿"
reply-placeholder: "この投稿への返信..." reply-placeholder: "この投稿への返信..."
post-placeholder: "いまどうしてる?" post-placeholder: "いまどうしてる?"
attach-media-from-local: "デバイスからメディアを添付"
mk-search-posts: mk-search-posts:
empty: "「{}」に関する投稿は見つかりませんでした。" empty: "「{}」に関する投稿は見つかりませんでした。"

View File

@ -1,7 +1,7 @@
{ {
"name": "misskey", "name": "misskey",
"author": "syuilo <i@syuilo.com>", "author": "syuilo <i@syuilo.com>",
"version": "0.0.3272", "version": "0.0.3493",
"license": "MIT", "license": "MIT",
"description": "A miniblog-based SNS", "description": "A miniblog-based SNS",
"bugs": "https://github.com/syuilo/misskey/issues", "bugs": "https://github.com/syuilo/misskey/issues",
@ -22,131 +22,141 @@
"format": "gulp format" "format": "gulp format"
}, },
"dependencies": { "dependencies": {
"@fortawesome/fontawesome": "^1.0.0", "@fortawesome/fontawesome": "1.0.1",
"@fortawesome/fontawesome-free-brands": "^5.0.0", "@fortawesome/fontawesome-free-brands": "5.0.2",
"@fortawesome/fontawesome-free-regular": "^5.0.0", "@fortawesome/fontawesome-free-regular": "5.0.2",
"@fortawesome/fontawesome-free-solid": "^5.0.0", "@fortawesome/fontawesome-free-solid": "5.0.2",
"@prezzemolo/rap": "0.1.2", "@prezzemolo/rap": "0.1.2",
"@prezzemolo/zip": "0.0.3", "@prezzemolo/zip": "0.0.3",
"@types/bcryptjs": "2.4.1", "@types/bcryptjs": "2.4.1",
"@types/body-parser": "1.16.8", "@types/body-parser": "1.16.8",
"@types/chai": "4.0.6", "@types/chai": "4.1.2",
"@types/chai-http": "3.0.3", "@types/chai-http": "3.0.3",
"@types/compression": "0.0.35", "@types/compression": "0.0.35",
"@types/cookie": "0.3.1", "@types/cookie": "0.3.1",
"@types/cors": "2.8.3", "@types/cors": "2.8.3",
"@types/debug": "0.0.30", "@types/debug": "0.0.30",
"@types/deep-equal": "1.0.1", "@types/deep-equal": "1.0.1",
"@types/elasticsearch": "5.0.18", "@types/elasticsearch": "5.0.19",
"@types/event-stream": "3.3.33",
"@types/eventemitter3": "2.0.2", "@types/eventemitter3": "2.0.2",
"@types/express": "4.0.39", "@types/express": "4.11.1",
"@types/gm": "1.17.33", "@types/gm": "1.17.33",
"@types/gulp": "4.0.3", "@types/gulp": "3.8.36",
"@types/gulp-htmlmin": "1.3.31", "@types/gulp-htmlmin": "1.3.31",
"@types/gulp-mocha": "0.0.31", "@types/gulp-mocha": "0.0.31",
"@types/gulp-rename": "0.0.33", "@types/gulp-rename": "0.0.33",
"@types/gulp-replace": "0.0.31", "@types/gulp-replace": "0.0.31",
"@types/gulp-uglify": "3.0.3", "@types/gulp-uglify": "3.0.3",
"@types/gulp-util": "3.0.34", "@types/gulp-util": "3.0.34",
"@types/inquirer": "0.0.35", "@types/inquirer": "0.0.36",
"@types/is-root": "1.0.0", "@types/is-root": "1.0.0",
"@types/is-url": "1.2.28", "@types/is-url": "1.2.28",
"@types/js-yaml": "3.10.1", "@types/js-yaml": "3.10.1",
"@types/mocha": "2.2.44", "@types/license-checker": "^15.0.0",
"@types/mongodb": "2.2.16", "@types/mkdirp": "0.5.2",
"@types/monk": "1.0.6", "@types/mocha": "2.2.47",
"@types/mongodb": "3.0.5",
"@types/monk": "6.0.0",
"@types/morgan": "1.7.35", "@types/morgan": "1.7.35",
"@types/ms": "0.7.30", "@types/ms": "0.7.30",
"@types/multer": "1.3.6", "@types/multer": "1.3.6",
"@types/node": "8.0.57", "@types/node": "9.4.0",
"@types/page": "1.5.32", "@types/page": "1.5.32",
"@types/proxy-addr": "2.0.0", "@types/proxy-addr": "2.0.0",
"@types/pug": "2.0.4",
"@types/qrcode": "0.8.0",
"@types/ratelimiter": "2.1.28", "@types/ratelimiter": "2.1.28",
"@types/redis": "2.8.1", "@types/redis": "2.8.5",
"@types/request": "2.0.8", "@types/request": "2.47.0",
"@types/rimraf": "2.0.2", "@types/rimraf": "2.0.2",
"@types/riot": "3.6.1", "@types/riot": "3.6.1",
"@types/seedrandom": "2.4.27", "@types/seedrandom": "2.4.27",
"@types/serve-favicon": "2.2.30", "@types/serve-favicon": "2.2.30",
"@types/speakeasy": "2.0.2",
"@types/tmp": "0.0.33", "@types/tmp": "0.0.33",
"@types/uuid": "3.4.3", "@types/uuid": "3.4.3",
"@types/webpack": "3.8.1", "@types/webpack": "3.8.4",
"@types/webpack-stream": "3.2.8", "@types/webpack-stream": "3.2.8",
"@types/websocket": "0.0.35", "@types/websocket": "0.0.36",
"accesses": "2.5.0", "accesses": "2.5.0",
"animejs": "2.2.0", "animejs": "2.2.0",
"autwh": "0.0.1", "autwh": "0.0.1",
"awesome-typescript-loader": "3.4.1", "awesome-typescript-loader": "3.4.1",
"bcryptjs": "2.4.3", "bcryptjs": "2.4.3",
"body-parser": "1.18.2", "body-parser": "1.18.2",
"cafy": "3.2.0", "cafy": "3.2.1",
"chai": "4.1.2", "chai": "4.1.2",
"chai-http": "3.0.0", "chai-http": "3.0.0",
"chalk": "2.3.0", "chalk": "2.3.0",
"compression": "1.7.1", "compression": "1.7.1",
"cookie": "0.3.1", "cookie": "0.3.1",
"cors": "2.8.4", "cors": "2.8.4",
"cropperjs": "1.1.3", "cropperjs": "1.2.2",
"css-loader": "0.28.7", "css-loader": "0.28.9",
"debug": "3.1.0", "debug": "3.1.0",
"deep-equal": "1.0.1", "deep-equal": "1.0.1",
"deepcopy": "0.6.3", "deepcopy": "0.6.3",
"diskusage": "0.2.4", "diskusage": "0.2.4",
"elasticsearch": "14.0.0", "elasticsearch": "14.1.0",
"escape-regexp": "0.0.1", "escape-regexp": "0.0.1",
"event-stream": "3.3.4",
"eventemitter3": "3.0.0", "eventemitter3": "3.0.0",
"exif-js": "2.3.0",
"express": "4.16.2", "express": "4.16.2",
"file-type": "7.4.0", "file-type": "7.5.0",
"fuckadblock": "3.2.1", "fuckadblock": "3.2.1",
"gm": "1.23.0", "gm": "1.23.1",
"gulp": "3.9.1", "gulp": "3.9.1",
"gulp-cssnano": "2.1.2", "gulp-cssnano": "2.1.2",
"gulp-htmlmin": "3.0.0", "gulp-htmlmin": "4.0.0",
"gulp-imagemin": "4.0.0", "gulp-imagemin": "4.1.0",
"gulp-mocha": "4.3.1", "gulp-mocha": "5.0.0",
"gulp-pug": "3.3.0", "gulp-pug": "3.3.0",
"gulp-rename": "1.2.2", "gulp-rename": "1.2.2",
"gulp-replace": "0.6.1", "gulp-replace": "0.6.1",
"gulp-stylus": "2.7.0",
"gulp-tslint": "8.1.2", "gulp-tslint": "8.1.2",
"gulp-typescript": "3.2.3", "gulp-typescript": "3.2.4",
"gulp-uglify": "3.0.0", "gulp-uglify": "3.0.0",
"gulp-util": "3.0.8", "gulp-util": "3.0.8",
"inquirer": "4.0.1", "highlight.js": "9.12.0",
"inquirer": "5.0.1",
"is-root": "1.0.0", "is-root": "1.0.0",
"is-url": "1.2.2", "is-url": "1.2.2",
"js-yaml": "3.10.0", "js-yaml": "3.10.0",
"license-checker": "16.0.0",
"mecab-async": "0.1.2", "mecab-async": "0.1.2",
"mocha": "4.0.1", "mkdirp": "0.5.1",
"mocha": "5.0.0",
"moji": "0.5.1", "moji": "0.5.1",
"mongodb": "2.2.33", "mongodb": "3.0.2",
"monk": "6.0.5", "monk": "6.0.5",
"morgan": "1.9.0", "morgan": "1.9.0",
"ms": "2.1.1", "ms": "2.1.1",
"multer": "1.3.0", "multer": "1.3.0",
"nprogress": "0.2.0", "nprogress": "0.2.0",
"os-utils": "0.0.14", "os-utils": "0.0.14",
"page": "1.7.1", "page": "1.8.3",
"pictograph": "2.1.2", "pictograph": "2.1.5",
"prominence": "0.2.0", "prominence": "0.2.0",
"proxy-addr": "2.0.2", "proxy-addr": "2.0.2",
"pug": "2.0.0-rc.4", "pug": "2.0.0-rc.4",
"qrcode": "1.2.0",
"ratelimiter": "3.0.3", "ratelimiter": "3.0.3",
"recaptcha-promise": "0.1.3", "recaptcha-promise": "0.1.3",
"reconnecting-websocket": "3.2.2", "reconnecting-websocket": "3.2.2",
"redis": "2.8.0", "redis": "2.8.0",
"request": "2.83.0", "request": "2.83.0",
"rimraf": "2.6.2", "rimraf": "2.6.2",
"riot": "3.7.4", "riot": "3.8.1",
"riot-tag-loader": "1.0.0", "riot-tag-loader": "2.0.2",
"rndstr": "1.0.0", "rndstr": "1.0.0",
"s-age": "1.1.0", "s-age": "1.1.2",
"seedrandom": "^2.4.3", "seedrandom": "2.4.3",
"serve-favicon": "2.4.5", "serve-favicon": "2.4.5",
"sortablejs": "1.7.0", "sortablejs": "1.7.0",
"speakeasy": "2.0.0",
"string-replace-webpack-plugin": "0.1.3", "string-replace-webpack-plugin": "0.1.3",
"style-loader": "0.19.0", "style-loader": "0.20.1",
"stylus": "0.54.5", "stylus": "0.54.5",
"stylus-loader": "3.0.1", "stylus-loader": "3.0.1",
"summaly": "2.0.3", "summaly": "2.0.3",
@ -155,12 +165,12 @@
"tcp-port-used": "0.1.2", "tcp-port-used": "0.1.2",
"textarea-caret": "3.0.2", "textarea-caret": "3.0.2",
"tmp": "0.0.33", "tmp": "0.0.33",
"ts-node": "3.3.0", "ts-node": "4.1.0",
"tslint": "5.8.0", "tslint": "5.9.1",
"typescript": "2.6.2", "typescript": "2.7.1",
"uglify-es": "3.2.0", "uglify-es": "3.3.9",
"uglifyjs-webpack-plugin": "1.1.2", "uglifyjs-webpack-plugin": "1.1.8",
"uuid": "3.1.0", "uuid": "3.2.1",
"vhost": "3.0.2", "vhost": "3.0.2",
"web-push": "3.2.5", "web-push": "3.2.5",
"webpack": "3.10.0", "webpack": "3.10.0",

View File

@ -5,17 +5,21 @@ import * as stream from 'stream';
import * as mongodb from 'mongodb'; import * as mongodb from 'mongodb';
import * as crypto from 'crypto'; import * as crypto from 'crypto';
import * as gm from 'gm'; import * as _gm from 'gm';
import * as debug from 'debug'; import * as debug from 'debug';
import fileType = require('file-type'); import fileType = require('file-type');
import prominence = require('prominence'); import prominence = require('prominence');
import DriveFile, { getGridFSBucket } from '../models/drive-file'; import DriveFile, { getGridFSBucket } from '../models/drive-file';
import DriveFolder from '../models/drive-folder'; import DriveFolder from '../models/drive-folder';
import serialize from '../serializers/drive-file'; import { pack } from '../models/drive-file';
import event, { publishDriveStream } from '../event'; import event, { publishDriveStream } from '../event';
import config from '../../conf'; import config from '../../conf';
const gm = _gm.subClass({
imageMagick: true
});
const log = debug('misskey:register-drive-file'); const log = debug('misskey:register-drive-file');
const tmpFile = (): Promise<string> => new Promise((resolve, reject) => { const tmpFile = (): Promise<string> => new Promise((resolve, reject) => {
@ -106,8 +110,32 @@ const addFile = async (
} }
} }
const [properties, folder] = await Promise.all([ const [wh, averageColor, folder] = await Promise.all([
// properties // Width and height (when image)
(async () => {
// 画像かどうか
if (!/^image\/.*$/.test(mime)) {
return null;
}
const imageType = mime.split('/')[1];
// 画像でもPNGかJPEGかGIFでないならスキップ
if (imageType != 'png' && imageType != 'jpeg' && imageType != 'gif') {
return null;
}
log('calculate image width and height...');
// Calculate width and height
const g = gm(fs.createReadStream(path), name);
const size = await prominence(g).size();
log(`image width and height is calculated: ${size.width}, ${size.height}`);
return [size.width, size.height];
})(),
// average color (when image)
(async () => { (async () => {
// 画像かどうか // 画像かどうか
if (!/^image\/.*$/.test(mime)) { if (!/^image\/.*$/.test(mime)) {
@ -121,17 +149,20 @@ const addFile = async (
return null; return null;
} }
// If the file is an image, calculate width and height to save in property log('calculate average color...');
const g = gm(fs.createReadStream(path), name);
const size = await prominence(g).size();
const properties = {
width: size.width,
height: size.height
};
log('image width and height is calculated'); const buffer = await prominence(gm(fs.createReadStream(path), name)
.setFormat('ppm')
.resize(1, 1)) // 1pxのサイズに縮小して平均色を取得するというハック
.toBuffer();
return properties; const r = buffer.readUInt8(buffer.length - 3);
const g = buffer.readUInt8(buffer.length - 2);
const b = buffer.readUInt8(buffer.length - 1);
log(`average color is calculated: ${r}, ${g}, ${b}`);
return [r, g, b];
})(), })(),
// folder // folder
(async () => { (async () => {
@ -181,6 +212,17 @@ const addFile = async (
const readable = fs.createReadStream(path); const readable = fs.createReadStream(path);
const properties = {};
if (wh) {
properties['width'] = wh[0];
properties['height'] = wh[1];
}
if (averageColor) {
properties['average_color'] = averageColor;
}
return addToGridFS(detectedName, readable, mime, { return addToGridFS(detectedName, readable, mime, {
user_id: user._id, user_id: user._id,
folder_id: folder !== null ? folder._id : null, folder_id: folder !== null ? folder._id : null,
@ -224,11 +266,11 @@ export default (user: any, file: string | stream.Readable, ...args) => new Promi
} }
rej(new Error('un-compatible file.')); rej(new Error('un-compatible file.'));
}) })
.then(([path, remove]): Promise<any> => new Promise((res, rej) => { .then(([path, shouldCleanup]): Promise<any> => new Promise((res, rej) => {
addFile(user, path, ...args) addFile(user, path, ...args)
.then(file => { .then(file => {
res(file); res(file);
if (remove) { if (shouldCleanup) {
fs.unlink(path, (e) => { fs.unlink(path, (e) => {
if (e) log(e.stack); if (e) log(e.stack);
}); });
@ -240,7 +282,7 @@ export default (user: any, file: string | stream.Readable, ...args) => new Promi
log(`drive file has been created ${file._id}`); log(`drive file has been created ${file._id}`);
resolve(file); resolve(file);
serialize(file).then(serializedFile => { pack(file).then(serializedFile => {
// Publish drive_file_created event // Publish drive_file_created event
event(user._id, 'drive_file_created', serializedFile); event(user._id, 'drive_file_created', serializedFile);
publishDriveStream(user._id, 'file_created', serializedFile); publishDriveStream(user._id, 'file_created', serializedFile);

View File

@ -1,7 +1,8 @@
import * as mongo from 'mongodb'; import * as mongo from 'mongodb';
import Notification from '../models/notification'; import Notification from '../models/notification';
import Mute from '../models/mute';
import event from '../event'; import event from '../event';
import serialize from '../serializers/notification'; import { pack } from '../models/notification';
export default ( export default (
notifiee: mongo.ObjectID, notifiee: mongo.ObjectID,
@ -26,13 +27,24 @@ export default (
// Publish notification event // Publish notification event
event(notifiee, 'notification', event(notifiee, 'notification',
await serialize(notification)); await pack(notification));
// 3秒経っても(今回作成した)通知が既読にならなかったら「未読の通知がありますよ」イベントを発行する // 3秒経っても(今回作成した)通知が既読にならなかったら「未読の通知がありますよ」イベントを発行する
setTimeout(async () => { setTimeout(async () => {
const fresh = await Notification.findOne({ _id: notification._id }, { is_read: true }); const fresh = await Notification.findOne({ _id: notification._id }, { is_read: true });
if (!fresh.is_read) { if (!fresh.is_read) {
event(notifiee, 'unread_notification', await serialize(notification)); //#region ただしミュートしているユーザーからの通知なら無視
const mute = await Mute.find({
muter_id: notifiee,
deleted_at: { $exists: false }
});
const mutedUserIds = mute.map(m => m.mutee_id.toString());
if (mutedUserIds.indexOf(notifier.toString()) != -1) {
return;
}
//#endregion
event(notifiee, 'unread_notification', await pack(notification));
} }
}, 3000); }, 3000);
}); });

View File

@ -155,6 +155,21 @@ const endpoints: Endpoint[] = [
name: 'i', name: 'i',
withCredential: true withCredential: true
}, },
{
name: 'i/2fa/register',
withCredential: true,
secure: true
},
{
name: 'i/2fa/unregister',
withCredential: true,
secure: true
},
{
name: 'i/2fa/done',
withCredential: true,
secure: true
},
{ {
name: 'i/update', name: 'i/update',
withCredential: true, withCredential: true,
@ -171,11 +186,13 @@ const endpoints: Endpoint[] = [
}, },
{ {
name: 'i/change_password', name: 'i/change_password',
withCredential: true withCredential: true,
secure: true
}, },
{ {
name: 'i/regenerate_token', name: 'i/regenerate_token',
withCredential: true withCredential: true,
secure: true
}, },
{ {
name: 'i/pin', name: 'i/pin',
@ -205,6 +222,23 @@ const endpoints: Endpoint[] = [
withCredential: true, withCredential: true,
kind: 'notification-read' kind: 'notification-read'
}, },
{
name: 'mute/create',
withCredential: true,
kind: 'account/write'
},
{
name: 'mute/delete',
withCredential: true,
kind: 'account/write'
},
{
name: 'mute/list',
withCredential: true,
kind: 'account/read'
},
{ {
name: 'notifications/get_unread_count', name: 'notifications/get_unread_count',
withCredential: true, withCredential: true,

View File

@ -35,10 +35,13 @@ module.exports = (params) => new Promise(async (res, rej) => {
{ deleted_at: { $gt: startTime } } { deleted_at: { $gt: startTime } }
] ]
}, { }, {
_id: false, sort: {
post_id: false _id: -1
}, { },
sort: { created_at: -1 } fields: {
_id: false,
post_id: false
}
}); });
const graph = []; const graph = [];

View File

@ -17,11 +17,14 @@ module.exports = params => new Promise(async (res, rej) => {
const users = await User const users = await User
.find({}, { .find({}, {
_id: false, sort: {
created_at: true, _id: -1
deleted_at: true },
}, { fields: {
sort: { created_at: -1 } _id: false,
created_at: true,
deleted_at: true
}
}); });
const graph = []; const graph = [];

View File

@ -3,9 +3,7 @@
*/ */
import rndstr from 'rndstr'; import rndstr from 'rndstr';
import $ from 'cafy'; import $ from 'cafy';
import App from '../../models/app'; import App, { isValidNameId, pack } from '../../models/app';
import { isValidNameId } from '../../models/app';
import serialize from '../../serializers/app';
/** /**
* @swagger * @swagger
@ -106,5 +104,5 @@ module.exports = async (params, user) => new Promise(async (res, rej) => {
}); });
// Response // Response
res(await serialize(app)); res(await pack(app));
}); });

View File

@ -2,8 +2,7 @@
* Module dependencies * Module dependencies
*/ */
import $ from 'cafy'; import $ from 'cafy';
import App from '../../models/app'; import App, { pack } from '../../models/app';
import serialize from '../../serializers/app';
/** /**
* @swagger * @swagger
@ -67,7 +66,7 @@ module.exports = (params, user, _, isSecure) => new Promise(async (res, rej) =>
} }
// Send response // Send response
res(await serialize(app, user, { res(await pack(app, user, {
includeSecret: isSecure && app.user_id.equals(user._id) includeSecret: isSecure && app.user_id.equals(user._id)
})); }));
}); });

View File

@ -2,8 +2,7 @@
* Module dependencies * Module dependencies
*/ */
import $ from 'cafy'; import $ from 'cafy';
import AuthSess from '../../../models/auth-session'; import AuthSess, { pack } from '../../../models/auth-session';
import serialize from '../../../serializers/auth-session';
/** /**
* @swagger * @swagger
@ -67,5 +66,5 @@ module.exports = (params, user) => new Promise(async (res, rej) => {
} }
// Response // Response
res(await serialize(session, user)); res(await pack(session, user));
}); });

View File

@ -5,7 +5,7 @@ import $ from 'cafy';
import App from '../../../models/app'; import App from '../../../models/app';
import AuthSess from '../../../models/auth-session'; import AuthSess from '../../../models/auth-session';
import AccessToken from '../../../models/access-token'; import AccessToken from '../../../models/access-token';
import serialize from '../../../serializers/user'; import { pack } from '../../../models/user';
/** /**
* @swagger * @swagger
@ -102,7 +102,7 @@ module.exports = (params) => new Promise(async (res, rej) => {
// Response // Response
res({ res({
access_token: accessToken.token, access_token: accessToken.token,
user: await serialize(session.user_id, null, { user: await pack(session.user_id, null, {
detail: true detail: true
}) })
}); });

View File

@ -2,8 +2,7 @@
* Module dependencies * Module dependencies
*/ */
import $ from 'cafy'; import $ from 'cafy';
import Channel from '../models/channel'; import Channel, { pack } from '../models/channel';
import serialize from '../serializers/channel';
/** /**
* Get all channels * Get all channels
@ -21,13 +20,13 @@ module.exports = (params, me) => new Promise(async (res, rej) => {
const [sinceId, sinceIdErr] = $(params.since_id).optional.id().$; const [sinceId, sinceIdErr] = $(params.since_id).optional.id().$;
if (sinceIdErr) return rej('invalid since_id param'); if (sinceIdErr) return rej('invalid since_id param');
// Get 'max_id' parameter // Get 'until_id' parameter
const [maxId, maxIdErr] = $(params.max_id).optional.id().$; const [untilId, untilIdErr] = $(params.until_id).optional.id().$;
if (maxIdErr) return rej('invalid max_id param'); if (untilIdErr) return rej('invalid until_id param');
// Check if both of since_id and max_id is specified // Check if both of since_id and until_id is specified
if (sinceId && maxId) { if (sinceId && untilId) {
return rej('cannot set since_id and max_id'); return rej('cannot set since_id and until_id');
} }
// Construct query // Construct query
@ -40,9 +39,9 @@ module.exports = (params, me) => new Promise(async (res, rej) => {
query._id = { query._id = {
$gt: sinceId $gt: sinceId
}; };
} else if (maxId) { } else if (untilId) {
query._id = { query._id = {
$lt: maxId $lt: untilId
}; };
} }
@ -55,5 +54,5 @@ module.exports = (params, me) => new Promise(async (res, rej) => {
// Serialize // Serialize
res(await Promise.all(channels.map(async channel => res(await Promise.all(channels.map(async channel =>
await serialize(channel, me)))); await pack(channel, me))));
}); });

View File

@ -4,7 +4,7 @@
import $ from 'cafy'; import $ from 'cafy';
import Channel from '../../models/channel'; import Channel from '../../models/channel';
import Watching from '../../models/channel-watching'; import Watching from '../../models/channel-watching';
import serialize from '../../serializers/channel'; import { pack } from '../../models/channel';
/** /**
* Create a channel * Create a channel
@ -28,7 +28,7 @@ module.exports = async (params, user) => new Promise(async (res, rej) => {
}); });
// Response // Response
res(await serialize(channel)); res(await pack(channel));
// Create Watching // Create Watching
await Watching.insert({ await Watching.insert({

View File

@ -3,8 +3,7 @@
*/ */
import $ from 'cafy'; import $ from 'cafy';
import { default as Channel, IChannel } from '../../models/channel'; import { default as Channel, IChannel } from '../../models/channel';
import Post from '../../models/post'; import Post, { pack } from '../../models/post';
import serialize from '../../serializers/post';
/** /**
* Show a posts of a channel * Show a posts of a channel
@ -22,13 +21,13 @@ module.exports = (params, user) => new Promise(async (res, rej) => {
const [sinceId, sinceIdErr] = $(params.since_id).optional.id().$; const [sinceId, sinceIdErr] = $(params.since_id).optional.id().$;
if (sinceIdErr) return rej('invalid since_id param'); if (sinceIdErr) return rej('invalid since_id param');
// Get 'max_id' parameter // Get 'until_id' parameter
const [maxId, maxIdErr] = $(params.max_id).optional.id().$; const [untilId, untilIdErr] = $(params.until_id).optional.id().$;
if (maxIdErr) return rej('invalid max_id param'); if (untilIdErr) return rej('invalid until_id param');
// Check if both of since_id and max_id is specified // Check if both of since_id and until_id is specified
if (sinceId && maxId) { if (sinceId && untilId) {
return rej('cannot set since_id and max_id'); return rej('cannot set since_id and until_id');
} }
// Get 'channel_id' parameter // Get 'channel_id' parameter
@ -58,9 +57,9 @@ module.exports = (params, user) => new Promise(async (res, rej) => {
query._id = { query._id = {
$gt: sinceId $gt: sinceId
}; };
} else if (maxId) { } else if (untilId) {
query._id = { query._id = {
$lt: maxId $lt: untilId
}; };
} }
//#endregion Construct query //#endregion Construct query
@ -74,6 +73,6 @@ module.exports = (params, user) => new Promise(async (res, rej) => {
// Serialize // Serialize
res(await Promise.all(posts.map(async (post) => res(await Promise.all(posts.map(async (post) =>
await serialize(post, user) await pack(post, user)
))); )));
}); });

View File

@ -2,8 +2,7 @@
* Module dependencies * Module dependencies
*/ */
import $ from 'cafy'; import $ from 'cafy';
import { default as Channel, IChannel } from '../../models/channel'; import Channel, { IChannel, pack } from '../../models/channel';
import serialize from '../../serializers/channel';
/** /**
* Show a channel * Show a channel
@ -27,5 +26,5 @@ module.exports = (params, user) => new Promise(async (res, rej) => {
} }
// Serialize // Serialize
res(await serialize(channel, user)); res(await pack(channel, user));
}); });

View File

@ -2,8 +2,7 @@
* Module dependencies * Module dependencies
*/ */
import $ from 'cafy'; import $ from 'cafy';
import DriveFile from '../../models/drive-file'; import DriveFile, { pack } from '../../models/drive-file';
import serialize from '../../serializers/drive-file';
/** /**
* Get drive files * Get drive files
@ -22,13 +21,13 @@ module.exports = async (params, user, app) => {
const [sinceId, sinceIdErr] = $(params.since_id).optional.id().$; const [sinceId, sinceIdErr] = $(params.since_id).optional.id().$;
if (sinceIdErr) throw 'invalid since_id param'; if (sinceIdErr) throw 'invalid since_id param';
// Get 'max_id' parameter // Get 'until_id' parameter
const [maxId, maxIdErr] = $(params.max_id).optional.id().$; const [untilId, untilIdErr] = $(params.until_id).optional.id().$;
if (maxIdErr) throw 'invalid max_id param'; if (untilIdErr) throw 'invalid until_id param';
// Check if both of since_id and max_id is specified // Check if both of since_id and until_id is specified
if (sinceId && maxId) { if (sinceId && untilId) {
throw 'cannot set since_id and max_id'; throw 'cannot set since_id and until_id';
} }
// Get 'folder_id' parameter // Get 'folder_id' parameter
@ -52,9 +51,9 @@ module.exports = async (params, user, app) => {
query._id = { query._id = {
$gt: sinceId $gt: sinceId
}; };
} else if (maxId) { } else if (untilId) {
query._id = { query._id = {
$lt: maxId $lt: untilId
}; };
} }
if (type) { if (type) {
@ -69,6 +68,6 @@ module.exports = async (params, user, app) => {
}); });
// Serialize // Serialize
const _files = await Promise.all(files.map(file => serialize(file))); const _files = await Promise.all(files.map(file => pack(file)));
return _files; return _files;
}; };

View File

@ -2,8 +2,7 @@
* Module dependencies * Module dependencies
*/ */
import $ from 'cafy'; import $ from 'cafy';
import { validateFileName } from '../../../models/drive-file'; import { validateFileName, pack } from '../../../models/drive-file';
import serialize from '../../../serializers/drive-file';
import create from '../../../common/add-file-to-drive'; import create from '../../../common/add-file-to-drive';
/** /**
@ -38,9 +37,15 @@ module.exports = async (file, params, user): Promise<any> => {
const [folderId = null, folderIdErr] = $(params.folder_id).optional.nullable.id().$; const [folderId = null, folderIdErr] = $(params.folder_id).optional.nullable.id().$;
if (folderIdErr) throw 'invalid folder_id param'; if (folderIdErr) throw 'invalid folder_id param';
// Create file try {
const driveFile = await create(user, file.path, name, null, folderId); // Create file
const driveFile = await create(user, file.path, name, null, folderId);
// Serialize // Serialize
return serialize(driveFile); return pack(driveFile);
} catch (e) {
console.error(e);
throw e;
}
}; };

View File

@ -2,8 +2,7 @@
* Module dependencies * Module dependencies
*/ */
import $ from 'cafy'; import $ from 'cafy';
import DriveFile from '../../../models/drive-file'; import DriveFile, { pack } from '../../../models/drive-file';
import serialize from '../../../serializers/drive-file';
/** /**
* Find a file(s) * Find a file(s)
@ -31,5 +30,5 @@ module.exports = (params, user) => new Promise(async (res, rej) => {
// Serialize // Serialize
res(await Promise.all(files.map(async file => res(await Promise.all(files.map(async file =>
await serialize(file)))); await pack(file))));
}); });

View File

@ -2,8 +2,7 @@
* Module dependencies * Module dependencies
*/ */
import $ from 'cafy'; import $ from 'cafy';
import DriveFile from '../../../models/drive-file'; import DriveFile, { pack } from '../../../models/drive-file';
import serialize from '../../../serializers/drive-file';
/** /**
* Show a file * Show a file
@ -29,7 +28,7 @@ module.exports = async (params, user) => {
} }
// Serialize // Serialize
const _file = await serialize(file, { const _file = await pack(file, {
detail: true detail: true
}); });

View File

@ -3,9 +3,7 @@
*/ */
import $ from 'cafy'; import $ from 'cafy';
import DriveFolder from '../../../models/drive-folder'; import DriveFolder from '../../../models/drive-folder';
import DriveFile from '../../../models/drive-file'; import DriveFile, { validateFileName, pack } from '../../../models/drive-file';
import { validateFileName } from '../../../models/drive-file';
import serialize from '../../../serializers/drive-file';
import { publishDriveStream } from '../../../event'; import { publishDriveStream } from '../../../event';
/** /**
@ -67,7 +65,7 @@ module.exports = (params, user) => new Promise(async (res, rej) => {
}); });
// Serialize // Serialize
const fileObj = await serialize(file); const fileObj = await pack(file);
// Response // Response
res(fileObj); res(fileObj);

View File

@ -3,8 +3,7 @@
*/ */
import * as URL from 'url'; import * as URL from 'url';
import $ from 'cafy'; import $ from 'cafy';
import { validateFileName } from '../../../models/drive-file'; import { validateFileName, pack } from '../../../models/drive-file';
import serialize from '../../../serializers/drive-file';
import create from '../../../common/add-file-to-drive'; import create from '../../../common/add-file-to-drive';
import * as debug from 'debug'; import * as debug from 'debug';
import * as tmp from 'tmp'; import * as tmp from 'tmp';
@ -63,5 +62,5 @@ module.exports = async (params, user): Promise<any> => {
if (e) log(e.stack); if (e) log(e.stack);
}); });
return serialize(driveFile); return pack(driveFile);
}; };

View File

@ -2,8 +2,7 @@
* Module dependencies * Module dependencies
*/ */
import $ from 'cafy'; import $ from 'cafy';
import DriveFolder from '../../models/drive-folder'; import DriveFolder, { pack } from '../../models/drive-folder';
import serialize from '../../serializers/drive-folder';
/** /**
* Get drive folders * Get drive folders
@ -22,13 +21,13 @@ module.exports = (params, user, app) => new Promise(async (res, rej) => {
const [sinceId, sinceIdErr] = $(params.since_id).optional.id().$; const [sinceId, sinceIdErr] = $(params.since_id).optional.id().$;
if (sinceIdErr) return rej('invalid since_id param'); if (sinceIdErr) return rej('invalid since_id param');
// Get 'max_id' parameter // Get 'until_id' parameter
const [maxId, maxIdErr] = $(params.max_id).optional.id().$; const [untilId, untilIdErr] = $(params.until_id).optional.id().$;
if (maxIdErr) return rej('invalid max_id param'); if (untilIdErr) return rej('invalid until_id param');
// Check if both of since_id and max_id is specified // Check if both of since_id and until_id is specified
if (sinceId && maxId) { if (sinceId && untilId) {
return rej('cannot set since_id and max_id'); return rej('cannot set since_id and until_id');
} }
// Get 'folder_id' parameter // Get 'folder_id' parameter
@ -48,9 +47,9 @@ module.exports = (params, user, app) => new Promise(async (res, rej) => {
query._id = { query._id = {
$gt: sinceId $gt: sinceId
}; };
} else if (maxId) { } else if (untilId) {
query._id = { query._id = {
$lt: maxId $lt: untilId
}; };
} }
@ -63,5 +62,5 @@ module.exports = (params, user, app) => new Promise(async (res, rej) => {
// Serialize // Serialize
res(await Promise.all(folders.map(async folder => res(await Promise.all(folders.map(async folder =>
await serialize(folder)))); await pack(folder))));
}); });

View File

@ -2,9 +2,7 @@
* Module dependencies * Module dependencies
*/ */
import $ from 'cafy'; import $ from 'cafy';
import DriveFolder from '../../../models/drive-folder'; import DriveFolder, { isValidFolderName, pack } from '../../../models/drive-folder';
import { isValidFolderName } from '../../../models/drive-folder';
import serialize from '../../../serializers/drive-folder';
import { publishDriveStream } from '../../../event'; import { publishDriveStream } from '../../../event';
/** /**
@ -47,7 +45,7 @@ module.exports = (params, user) => new Promise(async (res, rej) => {
}); });
// Serialize // Serialize
const folderObj = await serialize(folder); const folderObj = await pack(folder);
// Response // Response
res(folderObj); res(folderObj);

View File

@ -2,8 +2,7 @@
* Module dependencies * Module dependencies
*/ */
import $ from 'cafy'; import $ from 'cafy';
import DriveFolder from '../../../models/drive-folder'; import DriveFolder, { pack } from '../../../models/drive-folder';
import serialize from '../../../serializers/drive-folder';
/** /**
* Find a folder(s) * Find a folder(s)
@ -30,5 +29,5 @@ module.exports = (params, user) => new Promise(async (res, rej) => {
}); });
// Serialize // Serialize
res(await Promise.all(folders.map(folder => serialize(folder)))); res(await Promise.all(folders.map(folder => pack(folder))));
}); });

View File

@ -2,8 +2,7 @@
* Module dependencies * Module dependencies
*/ */
import $ from 'cafy'; import $ from 'cafy';
import DriveFolder from '../../../models/drive-folder'; import DriveFolder, { pack } from '../../../models/drive-folder';
import serialize from '../../../serializers/drive-folder';
/** /**
* Show a folder * Show a folder
@ -29,7 +28,7 @@ module.exports = (params, user) => new Promise(async (res, rej) => {
} }
// Serialize // Serialize
res(await serialize(folder, { res(await pack(folder, {
detail: true detail: true
})); }));
}); });

View File

@ -2,9 +2,7 @@
* Module dependencies * Module dependencies
*/ */
import $ from 'cafy'; import $ from 'cafy';
import DriveFolder from '../../../models/drive-folder'; import DriveFolder, { isValidFolderName, pack } from '../../../models/drive-folder';
import { isValidFolderName } from '../../../models/drive-folder';
import serialize from '../../../serializers/drive-folder';
import { publishDriveStream } from '../../../event'; import { publishDriveStream } from '../../../event';
/** /**
@ -91,7 +89,7 @@ module.exports = (params, user) => new Promise(async (res, rej) => {
}); });
// Serialize // Serialize
const folderObj = await serialize(folder); const folderObj = await pack(folder);
// Response // Response
res(folderObj); res(folderObj);

View File

@ -2,8 +2,7 @@
* Module dependencies * Module dependencies
*/ */
import $ from 'cafy'; import $ from 'cafy';
import DriveFile from '../../models/drive-file'; import DriveFile, { pack } from '../../models/drive-file';
import serialize from '../../serializers/drive-file';
/** /**
* Get drive stream * Get drive stream
@ -21,13 +20,13 @@ module.exports = (params, user) => new Promise(async (res, rej) => {
const [sinceId, sinceIdErr] = $(params.since_id).optional.id().$; const [sinceId, sinceIdErr] = $(params.since_id).optional.id().$;
if (sinceIdErr) return rej('invalid since_id param'); if (sinceIdErr) return rej('invalid since_id param');
// Get 'max_id' parameter // Get 'until_id' parameter
const [maxId, maxIdErr] = $(params.max_id).optional.id().$; const [untilId, untilIdErr] = $(params.until_id).optional.id().$;
if (maxIdErr) return rej('invalid max_id param'); if (untilIdErr) return rej('invalid until_id param');
// Check if both of since_id and max_id is specified // Check if both of since_id and until_id is specified
if (sinceId && maxId) { if (sinceId && untilId) {
return rej('cannot set since_id and max_id'); return rej('cannot set since_id and until_id');
} }
// Get 'type' parameter // Get 'type' parameter
@ -46,9 +45,9 @@ module.exports = (params, user) => new Promise(async (res, rej) => {
query._id = { query._id = {
$gt: sinceId $gt: sinceId
}; };
} else if (maxId) { } else if (untilId) {
query._id = { query._id = {
$lt: maxId $lt: untilId
}; };
} }
if (type) { if (type) {
@ -64,5 +63,5 @@ module.exports = (params, user) => new Promise(async (res, rej) => {
// Serialize // Serialize
res(await Promise.all(files.map(async file => res(await Promise.all(files.map(async file =>
await serialize(file)))); await pack(file))));
}); });

View File

@ -2,11 +2,10 @@
* Module dependencies * Module dependencies
*/ */
import $ from 'cafy'; import $ from 'cafy';
import User from '../../models/user'; import User, { pack as packUser } from '../../models/user';
import Following from '../../models/following'; import Following from '../../models/following';
import notify from '../../common/notify'; import notify from '../../common/notify';
import event from '../../event'; import event from '../../event';
import serializeUser from '../../serializers/user';
/** /**
* Follow a user * Follow a user
@ -77,8 +76,8 @@ module.exports = (params, user) => new Promise(async (res, rej) => {
}); });
// Publish follow event // Publish follow event
event(follower._id, 'follow', await serializeUser(followee, follower)); event(follower._id, 'follow', await packUser(followee, follower));
event(followee._id, 'followed', await serializeUser(follower, followee)); event(followee._id, 'followed', await packUser(follower, followee));
// Notify // Notify
notify(followee._id, follower._id, 'follow'); notify(followee._id, follower._id, 'follow');

View File

@ -2,10 +2,9 @@
* Module dependencies * Module dependencies
*/ */
import $ from 'cafy'; import $ from 'cafy';
import User from '../../models/user'; import User, { pack as packUser } from '../../models/user';
import Following from '../../models/following'; import Following from '../../models/following';
import event from '../../event'; import event from '../../event';
import serializeUser from '../../serializers/user';
/** /**
* Unfollow a user * Unfollow a user
@ -78,5 +77,5 @@ module.exports = (params, user) => new Promise(async (res, rej) => {
}); });
// Publish follow event // Publish follow event
event(follower._id, 'unfollow', await serializeUser(followee, follower)); event(follower._id, 'unfollow', await packUser(followee, follower));
}); });

View File

@ -1,8 +1,7 @@
/** /**
* Module dependencies * Module dependencies
*/ */
import User from '../models/user'; import User, { pack } from '../models/user';
import serialize from '../serializers/user';
/** /**
* Show myself * Show myself
@ -15,7 +14,7 @@ import serialize from '../serializers/user';
*/ */
module.exports = (params, user, _, isSecure) => new Promise(async (res, rej) => { module.exports = (params, user, _, isSecure) => new Promise(async (res, rej) => {
// Serialize // Serialize
res(await serialize(user, user, { res(await pack(user, user, {
detail: true, detail: true,
includeSecrets: isSecure includeSecrets: isSecure
})); }));

View File

@ -0,0 +1,37 @@
/**
* Module dependencies
*/
import $ from 'cafy';
import * as speakeasy from 'speakeasy';
import User from '../../../models/user';
module.exports = async (params, user) => new Promise(async (res, rej) => {
// Get 'token' parameter
const [token, tokenErr] = $(params.token).string().$;
if (tokenErr) return rej('invalid token param');
const _token = token.replace(/\s/g, '');
if (user.two_factor_temp_secret == null) {
return rej('二段階認証の設定が開始されていません');
}
const verified = (speakeasy as any).totp.verify({
secret: user.two_factor_temp_secret,
encoding: 'base32',
token: _token
});
if (!verified) {
return rej('not verified');
}
await User.update(user._id, {
$set: {
two_factor_secret: user.two_factor_temp_secret,
two_factor_enabled: true
}
});
res();
});

View File

@ -0,0 +1,48 @@
/**
* Module dependencies
*/
import $ from 'cafy';
import * as bcrypt from 'bcryptjs';
import * as speakeasy from 'speakeasy';
import * as QRCode from 'qrcode';
import User from '../../../models/user';
import config from '../../../../conf';
module.exports = async (params, user) => new Promise(async (res, rej) => {
// Get 'password' parameter
const [password, passwordErr] = $(params.password).string().$;
if (passwordErr) return rej('invalid password param');
// Compare password
const same = await bcrypt.compare(password, user.password);
if (!same) {
return rej('incorrect password');
}
// Generate user's secret key
const secret = speakeasy.generateSecret({
length: 32
});
await User.update(user._id, {
$set: {
two_factor_temp_secret: secret.base32
}
});
// Get the data URL of the authenticator URL
QRCode.toDataURL(speakeasy.otpauthURL({
secret: secret.base32,
encoding: 'base32',
label: user.username,
issuer: config.host
}), (err, data_url) => {
res({
qr: data_url,
secret: secret.base32,
label: user.username,
issuer: config.host
});
});
});

View File

@ -0,0 +1,28 @@
/**
* Module dependencies
*/
import $ from 'cafy';
import * as bcrypt from 'bcryptjs';
import User from '../../../models/user';
module.exports = async (params, user) => new Promise(async (res, rej) => {
// Get 'password' parameter
const [password, passwordErr] = $(params.password).string().$;
if (passwordErr) return rej('invalid password param');
// Compare password
const same = await bcrypt.compare(password, user.password);
if (!same) {
return rej('incorrect password');
}
await User.update(user._id, {
$set: {
two_factor_secret: null,
two_factor_enabled: false
}
});
res();
});

View File

@ -3,7 +3,7 @@
*/ */
import $ from 'cafy'; import $ from 'cafy';
import AccessToken from '../../models/access-token'; import AccessToken from '../../models/access-token';
import serialize from '../../serializers/app'; import { pack } from '../../models/app';
/** /**
* Get authorized apps of my account * Get authorized apps of my account
@ -39,5 +39,5 @@ module.exports = (params, user) => new Promise(async (res, rej) => {
// Serialize // Serialize
res(await Promise.all(tokens.map(async token => res(await Promise.all(tokens.map(async token =>
await serialize(token.app_id)))); await pack(token.app_id))));
}); });

View File

@ -3,7 +3,7 @@
*/ */
import $ from 'cafy'; import $ from 'cafy';
import Favorite from '../../models/favorite'; import Favorite from '../../models/favorite';
import serialize from '../../serializers/post'; import { pack } from '../../models/post';
/** /**
* Get followers of a user * Get followers of a user
@ -39,6 +39,6 @@ module.exports = (params, user) => new Promise(async (res, rej) => {
// Serialize // Serialize
res(await Promise.all(favorites.map(async favorite => res(await Promise.all(favorites.map(async favorite =>
await serialize(favorite.post) await pack(favorite.post)
))); )));
}); });

View File

@ -3,7 +3,8 @@
*/ */
import $ from 'cafy'; import $ from 'cafy';
import Notification from '../../models/notification'; import Notification from '../../models/notification';
import serialize from '../../serializers/notification'; import Mute from '../../models/mute';
import { pack } from '../../models/notification';
import getFriends from '../../common/get-friends'; import getFriends from '../../common/get-friends';
import read from '../../common/read-notification'; import read from '../../common/read-notification';
@ -36,17 +37,27 @@ module.exports = (params, user) => new Promise(async (res, rej) => {
const [sinceId, sinceIdErr] = $(params.since_id).optional.id().$; const [sinceId, sinceIdErr] = $(params.since_id).optional.id().$;
if (sinceIdErr) return rej('invalid since_id param'); if (sinceIdErr) return rej('invalid since_id param');
// Get 'max_id' parameter // Get 'until_id' parameter
const [maxId, maxIdErr] = $(params.max_id).optional.id().$; const [untilId, untilIdErr] = $(params.until_id).optional.id().$;
if (maxIdErr) return rej('invalid max_id param'); if (untilIdErr) return rej('invalid until_id param');
// Check if both of since_id and max_id is specified // Check if both of since_id and until_id is specified
if (sinceId && maxId) { if (sinceId && untilId) {
return rej('cannot set since_id and max_id'); return rej('cannot set since_id and until_id');
} }
const mute = await Mute.find({
muter_id: user._id,
deleted_at: { $exists: false }
});
const query = { const query = {
notifiee_id: user._id notifiee_id: user._id,
$and: [{
notifier_id: {
$nin: mute.map(m => m.mutee_id)
}
}]
} as any; } as any;
const sort = { const sort = {
@ -54,12 +65,14 @@ module.exports = (params, user) => new Promise(async (res, rej) => {
}; };
if (following) { if (following) {
// ID list of the user $self and other users who the user follows // ID list of the user itself and other users who the user follows
const followingIds = await getFriends(user._id); const followingIds = await getFriends(user._id);
query.notifier_id = { query.$and.push({
$in: followingIds notifier_id: {
}; $in: followingIds
}
});
} }
if (type) { if (type) {
@ -73,9 +86,9 @@ module.exports = (params, user) => new Promise(async (res, rej) => {
query._id = { query._id = {
$gt: sinceId $gt: sinceId
}; };
} else if (maxId) { } else if (untilId) {
query._id = { query._id = {
$lt: maxId $lt: untilId
}; };
} }
@ -88,7 +101,7 @@ module.exports = (params, user) => new Promise(async (res, rej) => {
// Serialize // Serialize
res(await Promise.all(notifications.map(async notification => res(await Promise.all(notifications.map(async notification =>
await serialize(notification)))); await pack(notification))));
// Mark as read all // Mark as read all
if (notifications.length > 0 && markAsRead) { if (notifications.length > 0 && markAsRead) {

View File

@ -4,7 +4,7 @@
import $ from 'cafy'; import $ from 'cafy';
import User from '../../models/user'; import User from '../../models/user';
import Post from '../../models/post'; import Post from '../../models/post';
import serialize from '../../serializers/user'; import { pack } from '../../models/user';
/** /**
* Pin post * Pin post
@ -35,7 +35,7 @@ module.exports = async (params, user) => new Promise(async (res, rej) => {
}); });
// Serialize // Serialize
const iObj = await serialize(user, user, { const iObj = await pack(user, user, {
detail: true detail: true
}); });

View File

@ -2,8 +2,7 @@
* Module dependencies * Module dependencies
*/ */
import $ from 'cafy'; import $ from 'cafy';
import Signin from '../../models/signin'; import Signin, { pack } from '../../models/signin';
import serialize from '../../serializers/signin';
/** /**
* Get signin history of my account * Get signin history of my account
@ -21,13 +20,13 @@ module.exports = (params, user) => new Promise(async (res, rej) => {
const [sinceId, sinceIdErr] = $(params.since_id).optional.id().$; const [sinceId, sinceIdErr] = $(params.since_id).optional.id().$;
if (sinceIdErr) return rej('invalid since_id param'); if (sinceIdErr) return rej('invalid since_id param');
// Get 'max_id' parameter // Get 'until_id' parameter
const [maxId, maxIdErr] = $(params.max_id).optional.id().$; const [untilId, untilIdErr] = $(params.until_id).optional.id().$;
if (maxIdErr) return rej('invalid max_id param'); if (untilIdErr) return rej('invalid until_id param');
// Check if both of since_id and max_id is specified // Check if both of since_id and until_id is specified
if (sinceId && maxId) { if (sinceId && untilId) {
return rej('cannot set since_id and max_id'); return rej('cannot set since_id and until_id');
} }
const query = { const query = {
@ -43,9 +42,9 @@ module.exports = (params, user) => new Promise(async (res, rej) => {
query._id = { query._id = {
$gt: sinceId $gt: sinceId
}; };
} else if (maxId) { } else if (untilId) {
query._id = { query._id = {
$lt: maxId $lt: untilId
}; };
} }
@ -58,5 +57,5 @@ module.exports = (params, user) => new Promise(async (res, rej) => {
// Serialize // Serialize
res(await Promise.all(history.map(async record => res(await Promise.all(history.map(async record =>
await serialize(record)))); await pack(record))));
}); });

View File

@ -2,9 +2,7 @@
* Module dependencies * Module dependencies
*/ */
import $ from 'cafy'; import $ from 'cafy';
import User from '../../models/user'; import User, { isValidName, isValidDescription, isValidLocation, isValidBirthday, pack } from '../../models/user';
import { isValidName, isValidDescription, isValidLocation, isValidBirthday } from '../../models/user';
import serialize from '../../serializers/user';
import event from '../../event'; import event from '../../event';
import config from '../../../conf'; import config from '../../../conf';
@ -65,7 +63,7 @@ module.exports = async (params, user, _, isSecure) => new Promise(async (res, re
}); });
// Serialize // Serialize
const iObj = await serialize(user, user, { const iObj = await pack(user, user, {
detail: true, detail: true,
includeSecrets: isSecure includeSecrets: isSecure
}); });

View File

@ -3,7 +3,8 @@
*/ */
import $ from 'cafy'; import $ from 'cafy';
import History from '../../models/messaging-history'; import History from '../../models/messaging-history';
import serialize from '../../serializers/messaging-message'; import Mute from '../../models/mute';
import { pack } from '../../models/messaging-message';
/** /**
* Show messaging history * Show messaging history
@ -17,10 +18,18 @@ module.exports = (params, user) => new Promise(async (res, rej) => {
const [limit = 10, limitErr] = $(params.limit).optional.number().range(1, 100).$; const [limit = 10, limitErr] = $(params.limit).optional.number().range(1, 100).$;
if (limitErr) return rej('invalid limit param'); if (limitErr) return rej('invalid limit param');
const mute = await Mute.find({
muter_id: user._id,
deleted_at: { $exists: false }
});
// Get history // Get history
const history = await History const history = await History
.find({ .find({
user_id: user._id user_id: user._id,
partner: {
$nin: mute.map(m => m.mutee_id)
}
}, { }, {
limit: limit, limit: limit,
sort: { sort: {
@ -30,5 +39,5 @@ module.exports = (params, user) => new Promise(async (res, rej) => {
// Serialize // Serialize
res(await Promise.all(history.map(async h => res(await Promise.all(history.map(async h =>
await serialize(h.message, user)))); await pack(h.message, user))));
}); });

View File

@ -4,7 +4,7 @@
import $ from 'cafy'; import $ from 'cafy';
import Message from '../../models/messaging-message'; import Message from '../../models/messaging-message';
import User from '../../models/user'; import User from '../../models/user';
import serialize from '../../serializers/messaging-message'; import { pack } from '../../models/messaging-message';
import read from '../../common/read-messaging-message'; import read from '../../common/read-messaging-message';
/** /**
@ -44,13 +44,13 @@ module.exports = (params, user) => new Promise(async (res, rej) => {
const [sinceId, sinceIdErr] = $(params.since_id).optional.id().$; const [sinceId, sinceIdErr] = $(params.since_id).optional.id().$;
if (sinceIdErr) return rej('invalid since_id param'); if (sinceIdErr) return rej('invalid since_id param');
// Get 'max_id' parameter // Get 'until_id' parameter
const [maxId, maxIdErr] = $(params.max_id).optional.id().$; const [untilId, untilIdErr] = $(params.until_id).optional.id().$;
if (maxIdErr) return rej('invalid max_id param'); if (untilIdErr) return rej('invalid until_id param');
// Check if both of since_id and max_id is specified // Check if both of since_id and until_id is specified
if (sinceId && maxId) { if (sinceId && untilId) {
return rej('cannot set since_id and max_id'); return rej('cannot set since_id and until_id');
} }
const query = { const query = {
@ -72,9 +72,9 @@ module.exports = (params, user) => new Promise(async (res, rej) => {
query._id = { query._id = {
$gt: sinceId $gt: sinceId
}; };
} else if (maxId) { } else if (untilId) {
query._id = { query._id = {
$lt: maxId $lt: untilId
}; };
} }
@ -87,7 +87,7 @@ module.exports = (params, user) => new Promise(async (res, rej) => {
// Serialize // Serialize
res(await Promise.all(messages.map(async message => res(await Promise.all(messages.map(async message =>
await serialize(message, user, { await pack(message, user, {
populateRecipient: false populateRecipient: false
})))); }))));

View File

@ -6,8 +6,9 @@ import Message from '../../../models/messaging-message';
import { isValidText } from '../../../models/messaging-message'; import { isValidText } from '../../../models/messaging-message';
import History from '../../../models/messaging-history'; import History from '../../../models/messaging-history';
import User from '../../../models/user'; import User from '../../../models/user';
import Mute from '../../../models/mute';
import DriveFile from '../../../models/drive-file'; import DriveFile from '../../../models/drive-file';
import serialize from '../../../serializers/messaging-message'; import { pack } from '../../../models/messaging-message';
import publishUserStream from '../../../event'; import publishUserStream from '../../../event';
import { publishMessagingStream, publishMessagingIndexStream, pushSw } from '../../../event'; import { publishMessagingStream, publishMessagingIndexStream, pushSw } from '../../../event';
import config from '../../../../conf'; import config from '../../../../conf';
@ -78,7 +79,7 @@ module.exports = (params, user) => new Promise(async (res, rej) => {
}); });
// Serialize // Serialize
const messageObj = await serialize(message); const messageObj = await pack(message);
// Reponse // Reponse
res(messageObj); res(messageObj);
@ -97,6 +98,17 @@ module.exports = (params, user) => new Promise(async (res, rej) => {
setTimeout(async () => { setTimeout(async () => {
const freshMessage = await Message.findOne({ _id: message._id }, { is_read: true }); const freshMessage = await Message.findOne({ _id: message._id }, { is_read: true });
if (!freshMessage.is_read) { if (!freshMessage.is_read) {
//#region ただしミュートされているなら発行しない
const mute = await Mute.find({
muter_id: recipient._id,
deleted_at: { $exists: false }
});
const mutedUserIds = mute.map(m => m.mutee_id.toString());
if (mutedUserIds.indexOf(user._id.toString()) != -1) {
return;
}
//#endregion
publishUserStream(message.recipient_id, 'unread_messaging_message', messageObj); publishUserStream(message.recipient_id, 'unread_messaging_message', messageObj);
pushSw(message.recipient_id, 'unread_messaging_message', messageObj); pushSw(message.recipient_id, 'unread_messaging_message', messageObj);
} }

View File

@ -2,6 +2,7 @@
* Module dependencies * Module dependencies
*/ */
import Message from '../../models/messaging-message'; import Message from '../../models/messaging-message';
import Mute from '../../models/mute';
/** /**
* Get count of unread messages * Get count of unread messages
@ -11,8 +12,17 @@ import Message from '../../models/messaging-message';
* @return {Promise<any>} * @return {Promise<any>}
*/ */
module.exports = (params, user) => new Promise(async (res, rej) => { module.exports = (params, user) => new Promise(async (res, rej) => {
const mute = await Mute.find({
muter_id: user._id,
deleted_at: { $exists: false }
});
const mutedUserIds = mute.map(m => m.mutee_id);
const count = await Message const count = await Message
.count({ .count({
user_id: {
$nin: mutedUserIds
},
recipient_id: user._id, recipient_id: user._id,
is_read: false is_read: false
}); });

View File

@ -0,0 +1,61 @@
/**
* Module dependencies
*/
import $ from 'cafy';
import User from '../../models/user';
import Mute from '../../models/mute';
/**
* Mute a user
*
* @param {any} params
* @param {any} user
* @return {Promise<any>}
*/
module.exports = (params, user) => new Promise(async (res, rej) => {
const muter = user;
// Get 'user_id' parameter
const [userId, userIdErr] = $(params.user_id).id().$;
if (userIdErr) return rej('invalid user_id param');
// 自分自身
if (user._id.equals(userId)) {
return rej('mutee is yourself');
}
// Get mutee
const mutee = await User.findOne({
_id: userId
}, {
fields: {
data: false,
profile: false
}
});
if (mutee === null) {
return rej('user not found');
}
// Check if already muting
const exist = await Mute.findOne({
muter_id: muter._id,
mutee_id: mutee._id,
deleted_at: { $exists: false }
});
if (exist !== null) {
return rej('already muting');
}
// Create mute
await Mute.insert({
created_at: new Date(),
muter_id: muter._id,
mutee_id: mutee._id,
});
// Send response
res();
});

View File

@ -0,0 +1,63 @@
/**
* Module dependencies
*/
import $ from 'cafy';
import User from '../../models/user';
import Mute from '../../models/mute';
/**
* Unmute a user
*
* @param {any} params
* @param {any} user
* @return {Promise<any>}
*/
module.exports = (params, user) => new Promise(async (res, rej) => {
const muter = user;
// Get 'user_id' parameter
const [userId, userIdErr] = $(params.user_id).id().$;
if (userIdErr) return rej('invalid user_id param');
// Check if the mutee is yourself
if (user._id.equals(userId)) {
return rej('mutee is yourself');
}
// Get mutee
const mutee = await User.findOne({
_id: userId
}, {
fields: {
data: false,
profile: false
}
});
if (mutee === null) {
return rej('user not found');
}
// Check not muting
const exist = await Mute.findOne({
muter_id: muter._id,
mutee_id: mutee._id,
deleted_at: { $exists: false }
});
if (exist === null) {
return rej('already not muting');
}
// Delete mute
await Mute.update({
_id: exist._id
}, {
$set: {
deleted_at: new Date()
}
});
// Send response
res();
});

View File

@ -0,0 +1,73 @@
/**
* Module dependencies
*/
import $ from 'cafy';
import Mute from '../../models/mute';
import { pack } from '../../models/user';
import getFriends from '../../common/get-friends';
/**
* Get muted users of a user
*
* @param {any} params
* @param {any} me
* @return {Promise<any>}
*/
module.exports = (params, me) => new Promise(async (res, rej) => {
// Get 'iknow' parameter
const [iknow = false, iknowErr] = $(params.iknow).optional.boolean().$;
if (iknowErr) return rej('invalid iknow param');
// Get 'limit' parameter
const [limit = 30, limitErr] = $(params.limit).optional.number().range(1, 100).$;
if (limitErr) return rej('invalid limit param');
// Get 'cursor' parameter
const [cursor = null, cursorErr] = $(params.cursor).optional.id().$;
if (cursorErr) return rej('invalid cursor param');
// Construct query
const query = {
muter_id: me._id,
deleted_at: { $exists: false }
} as any;
if (iknow) {
// Get my friends
const myFriends = await getFriends(me._id);
query.mutee_id = {
$in: myFriends
};
}
// カーソルが指定されている場合
if (cursor) {
query._id = {
$lt: cursor
};
}
// Get mutes
const mutes = await Mute
.find(query, {
limit: limit + 1,
sort: { _id: -1 }
});
// 「次のページ」があるかどうか
const inStock = mutes.length === limit + 1;
if (inStock) {
mutes.pop();
}
// Serialize
const users = await Promise.all(mutes.map(async m =>
await pack(m.mutee_id, me, { detail: true })));
// Response
res({
users: users,
next: inStock ? mutes[mutes.length - 1]._id : null,
});
});

View File

@ -2,8 +2,7 @@
* Module dependencies * Module dependencies
*/ */
import $ from 'cafy'; import $ from 'cafy';
import App from '../../models/app'; import App, { pack } from '../../models/app';
import serialize from '../../serializers/app';
/** /**
* Get my apps * Get my apps
@ -37,5 +36,5 @@ module.exports = (params, user) => new Promise(async (res, rej) => {
// Reply // Reply
res(await Promise.all(apps.map(async app => res(await Promise.all(apps.map(async app =>
await serialize(app)))); await pack(app))));
}); });

View File

@ -2,6 +2,7 @@
* Module dependencies * Module dependencies
*/ */
import Notification from '../../models/notification'; import Notification from '../../models/notification';
import Mute from '../../models/mute';
/** /**
* Get count of unread notifications * Get count of unread notifications
@ -11,9 +12,18 @@ import Notification from '../../models/notification';
* @return {Promise<any>} * @return {Promise<any>}
*/ */
module.exports = (params, user) => new Promise(async (res, rej) => { module.exports = (params, user) => new Promise(async (res, rej) => {
const mute = await Mute.find({
muter_id: user._id,
deleted_at: { $exists: false }
});
const mutedUserIds = mute.map(m => m.mutee_id);
const count = await Notification const count = await Notification
.count({ .count({
notifiee_id: user._id, notifiee_id: user._id,
notifier_id: {
$nin: mutedUserIds
},
is_read: false is_read: false
}); });

View File

@ -2,8 +2,7 @@
* Module dependencies * Module dependencies
*/ */
import $ from 'cafy'; import $ from 'cafy';
import Post from '../models/post'; import Post, { pack } from '../models/post';
import serialize from '../serializers/post';
/** /**
* Lists all posts * Lists all posts
@ -36,13 +35,13 @@ module.exports = (params) => new Promise(async (res, rej) => {
const [sinceId, sinceIdErr] = $(params.since_id).optional.id().$; const [sinceId, sinceIdErr] = $(params.since_id).optional.id().$;
if (sinceIdErr) return rej('invalid since_id param'); if (sinceIdErr) return rej('invalid since_id param');
// Get 'max_id' parameter // Get 'until_id' parameter
const [maxId, maxIdErr] = $(params.max_id).optional.id().$; const [untilId, untilIdErr] = $(params.until_id).optional.id().$;
if (maxIdErr) return rej('invalid max_id param'); if (untilIdErr) return rej('invalid until_id param');
// Check if both of since_id and max_id is specified // Check if both of since_id and until_id is specified
if (sinceId && maxId) { if (sinceId && untilId) {
return rej('cannot set since_id and max_id'); return rej('cannot set since_id and until_id');
} }
// Construct query // Construct query
@ -55,9 +54,9 @@ module.exports = (params) => new Promise(async (res, rej) => {
query._id = { query._id = {
$gt: sinceId $gt: sinceId
}; };
} else if (maxId) { } else if (untilId) {
query._id = { query._id = {
$lt: maxId $lt: untilId
}; };
} }
@ -85,5 +84,5 @@ module.exports = (params) => new Promise(async (res, rej) => {
}); });
// Serialize // Serialize
res(await Promise.all(posts.map(async post => await serialize(post)))); res(await Promise.all(posts.map(async post => await pack(post))));
}); });

View File

@ -2,8 +2,7 @@
* Module dependencies * Module dependencies
*/ */
import $ from 'cafy'; import $ from 'cafy';
import Post from '../../models/post'; import Post, { pack } from '../../models/post';
import serialize from '../../serializers/post';
/** /**
* Show a context of a post * Show a context of a post
@ -60,5 +59,5 @@ module.exports = (params, user) => new Promise(async (res, rej) => {
// Serialize // Serialize
res(await Promise.all(context.map(async post => res(await Promise.all(context.map(async post =>
await serialize(post, user)))); await pack(post, user))));
}); });

View File

@ -8,10 +8,11 @@ import { default as Post, IPost, isValidText } from '../../models/post';
import { default as User, IUser } from '../../models/user'; import { default as User, IUser } from '../../models/user';
import { default as Channel, IChannel } from '../../models/channel'; import { default as Channel, IChannel } from '../../models/channel';
import Following from '../../models/following'; import Following from '../../models/following';
import Mute from '../../models/mute';
import DriveFile from '../../models/drive-file'; import DriveFile from '../../models/drive-file';
import Watching from '../../models/post-watching'; import Watching from '../../models/post-watching';
import ChannelWatching from '../../models/channel-watching'; import ChannelWatching from '../../models/channel-watching';
import serialize from '../../serializers/post'; import { pack } from '../../models/post';
import notify from '../../common/notify'; import notify from '../../common/notify';
import watch from '../../common/watch-post'; import watch from '../../common/watch-post';
import event, { pushSw, publishChannelStream } from '../../event'; import event, { pushSw, publishChannelStream } from '../../event';
@ -215,14 +216,20 @@ module.exports = (params, user: IUser, app) => new Promise(async (res, rej) => {
poll: poll, poll: poll,
text: text, text: text,
user_id: user._id, user_id: user._id,
app_id: app ? app._id : null app_id: app ? app._id : null,
// 以下非正規化データ
_reply: reply ? { user_id: reply.user_id } : undefined,
_repost: repost ? { user_id: repost.user_id } : undefined,
}); });
// Serialize // Serialize
const postObj = await serialize(post); const postObj = await pack(post);
// Reponse // Reponse
res(postObj); res({
created_post: postObj
});
//#region Post processes //#region Post processes
@ -234,7 +241,7 @@ module.exports = (params, user: IUser, app) => new Promise(async (res, rej) => {
const mentions = []; const mentions = [];
function addMention(mentionee, reason) { async function addMention(mentionee, reason) {
// Reject if already added // Reject if already added
if (mentions.some(x => x.equals(mentionee))) return; if (mentions.some(x => x.equals(mentionee))) return;
@ -243,8 +250,15 @@ module.exports = (params, user: IUser, app) => new Promise(async (res, rej) => {
// Publish event // Publish event
if (!user._id.equals(mentionee)) { if (!user._id.equals(mentionee)) {
event(mentionee, reason, postObj); const mentioneeMutes = await Mute.find({
pushSw(mentionee, reason, postObj); muter_id: mentionee,
deleted_at: { $exists: false }
});
const mentioneesMutedUserIds = mentioneeMutes.map(m => m.mutee_id.toString());
if (mentioneesMutedUserIds.indexOf(user._id.toString()) == -1) {
event(mentionee, reason, postObj);
pushSw(mentionee, reason, postObj);
}
} }
} }

View File

@ -4,7 +4,7 @@
import $ from 'cafy'; import $ from 'cafy';
import Post from '../../models/post'; import Post from '../../models/post';
import getFriends from '../../common/get-friends'; import getFriends from '../../common/get-friends';
import serialize from '../../serializers/post'; import { pack } from '../../models/post';
/** /**
* Get mentions of myself * Get mentions of myself
@ -27,13 +27,13 @@ module.exports = (params, user) => new Promise(async (res, rej) => {
const [sinceId, sinceIdErr] = $(params.since_id).optional.id().$; const [sinceId, sinceIdErr] = $(params.since_id).optional.id().$;
if (sinceIdErr) return rej('invalid since_id param'); if (sinceIdErr) return rej('invalid since_id param');
// Get 'max_id' parameter // Get 'until_id' parameter
const [maxId, maxIdErr] = $(params.max_id).optional.id().$; const [untilId, untilIdErr] = $(params.until_id).optional.id().$;
if (maxIdErr) return rej('invalid max_id param'); if (untilIdErr) return rej('invalid until_id param');
// Check if both of since_id and max_id is specified // Check if both of since_id and until_id is specified
if (sinceId && maxId) { if (sinceId && untilId) {
return rej('cannot set since_id and max_id'); return rej('cannot set since_id and until_id');
} }
// Construct query // Construct query
@ -58,9 +58,9 @@ module.exports = (params, user) => new Promise(async (res, rej) => {
query._id = { query._id = {
$gt: sinceId $gt: sinceId
}; };
} else if (maxId) { } else if (untilId) {
query._id = { query._id = {
$lt: maxId $lt: untilId
}; };
} }
@ -73,6 +73,6 @@ module.exports = (params, user) => new Promise(async (res, rej) => {
// Serialize // Serialize
res(await Promise.all(mentions.map(async mention => res(await Promise.all(mentions.map(async mention =>
await serialize(mention, user) await pack(mention, user)
))); )));
}); });

View File

@ -3,8 +3,7 @@
*/ */
import $ from 'cafy'; import $ from 'cafy';
import Vote from '../../../models/poll-vote'; import Vote from '../../../models/poll-vote';
import Post from '../../../models/post'; import Post, { pack } from '../../../models/post';
import serialize from '../../../serializers/post';
/** /**
* Get recommended polls * Get recommended polls
@ -56,5 +55,5 @@ module.exports = (params, user) => new Promise(async (res, rej) => {
// Serialize // Serialize
res(await Promise.all(posts.map(async post => res(await Promise.all(posts.map(async post =>
await serialize(post, user, { detail: true })))); await pack(post, user, { detail: true }))));
}); });

View File

@ -3,8 +3,7 @@
*/ */
import $ from 'cafy'; import $ from 'cafy';
import Post from '../../models/post'; import Post from '../../models/post';
import Reaction from '../../models/post-reaction'; import Reaction, { pack } from '../../models/post-reaction';
import serialize from '../../serializers/post-reaction';
/** /**
* Show reactions of a post * Show reactions of a post
@ -54,5 +53,5 @@ module.exports = (params, user) => new Promise(async (res, rej) => {
// Serialize // Serialize
res(await Promise.all(reactions.map(async reaction => res(await Promise.all(reactions.map(async reaction =>
await serialize(reaction, user)))); await pack(reaction, user))));
}); });

View File

@ -3,13 +3,12 @@
*/ */
import $ from 'cafy'; import $ from 'cafy';
import Reaction from '../../../models/post-reaction'; import Reaction from '../../../models/post-reaction';
import Post from '../../../models/post'; import Post, { pack as packPost } from '../../../models/post';
import { pack as packUser } from '../../../models/user';
import Watching from '../../../models/post-watching'; import Watching from '../../../models/post-watching';
import notify from '../../../common/notify'; import notify from '../../../common/notify';
import watch from '../../../common/watch-post'; import watch from '../../../common/watch-post';
import { publishPostStream, pushSw } from '../../../event'; import { publishPostStream, pushSw } from '../../../event';
import serializePost from '../../../serializers/post';
import serializeUser from '../../../serializers/user';
/** /**
* React to a post * React to a post
@ -90,8 +89,8 @@ module.exports = (params, user) => new Promise(async (res, rej) => {
}); });
pushSw(post.user_id, 'reaction', { pushSw(post.user_id, 'reaction', {
user: await serializeUser(user, post.user_id), user: await packUser(user, post.user_id),
post: await serializePost(post, post.user_id), post: await packPost(post, post.user_id),
reaction: reaction reaction: reaction
}); });

View File

@ -2,8 +2,7 @@
* Module dependencies * Module dependencies
*/ */
import $ from 'cafy'; import $ from 'cafy';
import Post from '../../models/post'; import Post, { pack } from '../../models/post';
import serialize from '../../serializers/post';
/** /**
* Show a replies of a post * Show a replies of a post
@ -50,5 +49,5 @@ module.exports = (params, user) => new Promise(async (res, rej) => {
// Serialize // Serialize
res(await Promise.all(replies.map(async post => res(await Promise.all(replies.map(async post =>
await serialize(post, user)))); await pack(post, user))));
}); });

View File

@ -2,8 +2,7 @@
* Module dependencies * Module dependencies
*/ */
import $ from 'cafy'; import $ from 'cafy';
import Post from '../../models/post'; import Post, { pack } from '../../models/post';
import serialize from '../../serializers/post';
/** /**
* Show a reposts of a post * Show a reposts of a post
@ -25,13 +24,13 @@ module.exports = (params, user) => new Promise(async (res, rej) => {
const [sinceId, sinceIdErr] = $(params.since_id).optional.id().$; const [sinceId, sinceIdErr] = $(params.since_id).optional.id().$;
if (sinceIdErr) return rej('invalid since_id param'); if (sinceIdErr) return rej('invalid since_id param');
// Get 'max_id' parameter // Get 'until_id' parameter
const [maxId, maxIdErr] = $(params.max_id).optional.id().$; const [untilId, untilIdErr] = $(params.until_id).optional.id().$;
if (maxIdErr) return rej('invalid max_id param'); if (untilIdErr) return rej('invalid until_id param');
// Check if both of since_id and max_id is specified // Check if both of since_id and until_id is specified
if (sinceId && maxId) { if (sinceId && untilId) {
return rej('cannot set since_id and max_id'); return rej('cannot set since_id and until_id');
} }
// Lookup post // Lookup post
@ -55,9 +54,9 @@ module.exports = (params, user) => new Promise(async (res, rej) => {
query._id = { query._id = {
$gt: sinceId $gt: sinceId
}; };
} else if (maxId) { } else if (untilId) {
query._id = { query._id = {
$lt: maxId $lt: untilId
}; };
} }
@ -70,5 +69,5 @@ module.exports = (params, user) => new Promise(async (res, rej) => {
// Serialize // Serialize
res(await Promise.all(reposts.map(async post => res(await Promise.all(reposts.map(async post =>
await serialize(post, user)))); await pack(post, user))));
}); });

View File

@ -1,12 +1,13 @@
/** /**
* Module dependencies * Module dependencies
*/ */
import * as mongo from 'mongodb';
import $ from 'cafy'; import $ from 'cafy';
const escapeRegexp = require('escape-regexp'); const escapeRegexp = require('escape-regexp');
import Post from '../../models/post'; import Post from '../../models/post';
import serialize from '../../serializers/post'; import User from '../../models/user';
import config from '../../../conf'; import Mute from '../../models/mute';
import getFriends from '../../common/get-friends';
import { pack } from '../../models/post';
/** /**
* Search a post * Search a post
@ -16,33 +17,331 @@ import config from '../../../conf';
* @return {Promise<any>} * @return {Promise<any>}
*/ */
module.exports = (params, me) => new Promise(async (res, rej) => { module.exports = (params, me) => new Promise(async (res, rej) => {
// Get 'query' parameter // Get 'text' parameter
const [query, queryError] = $(params.query).string().pipe(x => x != '').$; const [text, textError] = $(params.text).optional.string().$;
if (queryError) return rej('invalid query param'); if (textError) return rej('invalid text param');
// Get 'include_user_ids' parameter
const [includeUserIds = [], includeUserIdsErr] = $(params.include_user_ids).optional.array('id').$;
if (includeUserIdsErr) return rej('invalid include_user_ids param');
// Get 'exclude_user_ids' parameter
const [excludeUserIds = [], excludeUserIdsErr] = $(params.exclude_user_ids).optional.array('id').$;
if (excludeUserIdsErr) return rej('invalid exclude_user_ids param');
// Get 'include_user_usernames' parameter
const [includeUserUsernames = [], includeUserUsernamesErr] = $(params.include_user_usernames).optional.array('string').$;
if (includeUserUsernamesErr) return rej('invalid include_user_usernames param');
// Get 'exclude_user_usernames' parameter
const [excludeUserUsernames = [], excludeUserUsernamesErr] = $(params.exclude_user_usernames).optional.array('string').$;
if (excludeUserUsernamesErr) return rej('invalid exclude_user_usernames param');
// Get 'following' parameter
const [following = null, followingErr] = $(params.following).optional.nullable.boolean().$;
if (followingErr) return rej('invalid following param');
// Get 'mute' parameter
const [mute = 'mute_all', muteErr] = $(params.mute).optional.string().$;
if (muteErr) return rej('invalid mute param');
// Get 'reply' parameter
const [reply = null, replyErr] = $(params.reply).optional.nullable.boolean().$;
if (replyErr) return rej('invalid reply param');
// Get 'repost' parameter
const [repost = null, repostErr] = $(params.repost).optional.nullable.boolean().$;
if (repostErr) return rej('invalid repost param');
// Get 'media' parameter
const [media = null, mediaErr] = $(params.media).optional.nullable.boolean().$;
if (mediaErr) return rej('invalid media param');
// Get 'poll' parameter
const [poll = null, pollErr] = $(params.poll).optional.nullable.boolean().$;
if (pollErr) return rej('invalid poll param');
// Get 'since_date' parameter
const [sinceDate, sinceDateErr] = $(params.since_date).optional.number().$;
if (sinceDateErr) throw 'invalid since_date param';
// Get 'until_date' parameter
const [untilDate, untilDateErr] = $(params.until_date).optional.number().$;
if (untilDateErr) throw 'invalid until_date param';
// Get 'offset' parameter // Get 'offset' parameter
const [offset = 0, offsetErr] = $(params.offset).optional.number().min(0).$; const [offset = 0, offsetErr] = $(params.offset).optional.number().min(0).$;
if (offsetErr) return rej('invalid offset param'); if (offsetErr) return rej('invalid offset param');
// Get 'max' parameter // Get 'limit' parameter
const [max = 10, maxErr] = $(params.max).optional.number().range(1, 30).$; const [limit = 10, limitErr] = $(params.limit).optional.number().range(1, 30).$;
if (maxErr) return rej('invalid max param'); if (limitErr) return rej('invalid limit param');
// If Elasticsearch is available, search by $ let includeUsers = includeUserIds;
// If not, search by MongoDB if (includeUserUsernames != null) {
(config.elasticsearch.enable ? byElasticsearch : byNative) const ids = (await Promise.all(includeUserUsernames.map(async (username) => {
(res, rej, me, query, offset, max); const _user = await User.findOne({
username_lower: username.toLowerCase()
});
return _user ? _user._id : null;
}))).filter(id => id != null);
includeUsers = includeUsers.concat(ids);
}
let excludeUsers = excludeUserIds;
if (excludeUserUsernames != null) {
const ids = (await Promise.all(excludeUserUsernames.map(async (username) => {
const _user = await User.findOne({
username_lower: username.toLowerCase()
});
return _user ? _user._id : null;
}))).filter(id => id != null);
excludeUsers = excludeUsers.concat(ids);
}
search(res, rej, me, text, includeUsers, excludeUsers, following,
mute, reply, repost, media, poll, sinceDate, untilDate, offset, limit);
}); });
// Search by MongoDB async function search(
async function byNative(res, rej, me, query, offset, max) { res, rej, me, text, includeUserIds, excludeUserIds, following,
const escapedQuery = escapeRegexp(query); mute, reply, repost, media, poll, sinceDate, untilDate, offset, max) {
let q: any = {
$and: []
};
const push = x => q.$and.push(x);
if (text) {
// 完全一致検索
if (/"""(.+?)"""/.test(text)) {
const x = text.match(/"""(.+?)"""/)[1];
push({
text: x
});
} else {
push({
$and: text.split(' ').map(x => ({
// キーワードが-で始まる場合そのキーワードを除外する
text: x[0] == '-' ? {
$not: new RegExp(escapeRegexp(x.substr(1)))
} : new RegExp(escapeRegexp(x))
}))
});
}
}
if (includeUserIds && includeUserIds.length != 0) {
push({
user_id: {
$in: includeUserIds
}
});
} else if (excludeUserIds && excludeUserIds.length != 0) {
push({
user_id: {
$nin: excludeUserIds
}
});
}
if (following != null && me != null) {
const ids = await getFriends(me._id, false);
push({
user_id: following ? {
$in: ids
} : {
$nin: ids.concat(me._id)
}
});
}
if (me != null) {
const mutes = await Mute.find({
muter_id: me._id,
deleted_at: { $exists: false }
});
const mutedUserIds = mutes.map(m => m.mutee_id);
switch (mute) {
case 'mute_all':
push({
user_id: {
$nin: mutedUserIds
},
'_reply.user_id': {
$nin: mutedUserIds
},
'_repost.user_id': {
$nin: mutedUserIds
}
});
break;
case 'mute_related':
push({
'_reply.user_id': {
$nin: mutedUserIds
},
'_repost.user_id': {
$nin: mutedUserIds
}
});
break;
case 'mute_direct':
push({
user_id: {
$nin: mutedUserIds
}
});
break;
case 'direct_only':
push({
user_id: {
$in: mutedUserIds
}
});
break;
case 'related_only':
push({
$or: [{
'_reply.user_id': {
$in: mutedUserIds
}
}, {
'_repost.user_id': {
$in: mutedUserIds
}
}]
});
break;
case 'all_only':
push({
$or: [{
user_id: {
$in: mutedUserIds
}
}, {
'_reply.user_id': {
$in: mutedUserIds
}
}, {
'_repost.user_id': {
$in: mutedUserIds
}
}]
});
break;
}
}
if (reply != null) {
if (reply) {
push({
reply_id: {
$exists: true,
$ne: null
}
});
} else {
push({
$or: [{
reply_id: {
$exists: false
}
}, {
reply_id: null
}]
});
}
}
if (repost != null) {
if (repost) {
push({
repost_id: {
$exists: true,
$ne: null
}
});
} else {
push({
$or: [{
repost_id: {
$exists: false
}
}, {
repost_id: null
}]
});
}
}
if (media != null) {
if (media) {
push({
media_ids: {
$exists: true,
$ne: null
}
});
} else {
push({
$or: [{
media_ids: {
$exists: false
}
}, {
media_ids: null
}]
});
}
}
if (poll != null) {
if (poll) {
push({
poll: {
$exists: true,
$ne: null
}
});
} else {
push({
$or: [{
poll: {
$exists: false
}
}, {
poll: null
}]
});
}
}
if (sinceDate) {
push({
created_at: {
$gt: new Date(sinceDate)
}
});
}
if (untilDate) {
push({
created_at: {
$lt: new Date(untilDate)
}
});
}
if (q.$and.length == 0) {
q = {};
}
// Search posts // Search posts
const posts = await Post const posts = await Post
.find({ .find(q, {
text: new RegExp(escapedQuery)
}, {
sort: { sort: {
_id: -1 _id: -1
}, },
@ -52,68 +351,5 @@ async function byNative(res, rej, me, query, offset, max) {
// Serialize // Serialize
res(await Promise.all(posts.map(async post => res(await Promise.all(posts.map(async post =>
await serialize(post, me)))); await pack(post, me))));
}
// Search by Elasticsearch
async function byElasticsearch(res, rej, me, query, offset, max) {
const es = require('../../db/elasticsearch');
es.search({
index: 'misskey',
type: 'post',
body: {
size: max,
from: offset,
query: {
simple_query_string: {
fields: ['text'],
query: query,
default_operator: 'and'
}
},
sort: [
{ _doc: 'desc' }
],
highlight: {
pre_tags: ['<mark>'],
post_tags: ['</mark>'],
encoder: 'html',
fields: {
text: {}
}
}
}
}, async (error, response) => {
if (error) {
console.error(error);
return res(500);
}
if (response.hits.total === 0) {
return res([]);
}
const hits = response.hits.hits.map(hit => new mongo.ObjectID(hit._id));
// Fetch found posts
const posts = await Post
.find({
_id: {
$in: hits
}
}, {
sort: {
_id: -1
}
});
posts.map(post => {
post._highlight = response.hits.hits.filter(hit => post._id.equals(hit._id))[0].highlight.text[0];
});
// Serialize
res(await Promise.all(posts.map(async post =>
await serialize(post, me))));
});
} }

View File

@ -2,8 +2,7 @@
* Module dependencies * Module dependencies
*/ */
import $ from 'cafy'; import $ from 'cafy';
import Post from '../../models/post'; import Post, { pack } from '../../models/post';
import serialize from '../../serializers/post';
/** /**
* Show a post * Show a post
@ -27,7 +26,7 @@ module.exports = (params, user) => new Promise(async (res, rej) => {
} }
// Serialize // Serialize
res(await serialize(post, user, { res(await pack(post, user, {
detail: true detail: true
})); }));
}); });

View File

@ -4,9 +4,10 @@
import $ from 'cafy'; import $ from 'cafy';
import rap from '@prezzemolo/rap'; import rap from '@prezzemolo/rap';
import Post from '../../models/post'; import Post from '../../models/post';
import Mute from '../../models/mute';
import ChannelWatching from '../../models/channel-watching'; import ChannelWatching from '../../models/channel-watching';
import getFriends from '../../common/get-friends'; import getFriends from '../../common/get-friends';
import serialize from '../../serializers/post'; import { pack } from '../../models/post';
/** /**
* Get timeline of myself * Get timeline of myself
@ -25,32 +26,40 @@ module.exports = async (params, user, app) => {
const [sinceId, sinceIdErr] = $(params.since_id).optional.id().$; const [sinceId, sinceIdErr] = $(params.since_id).optional.id().$;
if (sinceIdErr) throw 'invalid since_id param'; if (sinceIdErr) throw 'invalid since_id param';
// Get 'max_id' parameter // Get 'until_id' parameter
const [maxId, maxIdErr] = $(params.max_id).optional.id().$; const [untilId, untilIdErr] = $(params.until_id).optional.id().$;
if (maxIdErr) throw 'invalid max_id param'; if (untilIdErr) throw 'invalid until_id param';
// Get 'since_date' parameter // Get 'since_date' parameter
const [sinceDate, sinceDateErr] = $(params.since_date).optional.number().$; const [sinceDate, sinceDateErr] = $(params.since_date).optional.number().$;
if (sinceDateErr) throw 'invalid since_date param'; if (sinceDateErr) throw 'invalid since_date param';
// Get 'max_date' parameter // Get 'until_date' parameter
const [maxDate, maxDateErr] = $(params.max_date).optional.number().$; const [untilDate, untilDateErr] = $(params.until_date).optional.number().$;
if (maxDateErr) throw 'invalid max_date param'; if (untilDateErr) throw 'invalid until_date param';
// Check if only one of since_id, max_id, since_date, max_date specified // Check if only one of since_id, until_id, since_date, until_date specified
if ([sinceId, maxId, sinceDate, maxDate].filter(x => x != null).length > 1) { if ([sinceId, untilId, sinceDate, untilDate].filter(x => x != null).length > 1) {
throw 'only one of since_id, max_id, since_date, max_date can be specified'; throw 'only one of since_id, until_id, since_date, until_date can be specified';
} }
const { followingIds, watchingChannelIds } = await rap({ const { followingIds, watchingChannelIds, mutedUserIds } = await rap({
// ID list of the user itself and other users who the user follows // ID list of the user itself and other users who the user follows
followingIds: getFriends(user._id), followingIds: getFriends(user._id),
// Watchしているチャンネルを取得 // Watchしているチャンネルを取得
watchingChannelIds: ChannelWatching.find({ watchingChannelIds: ChannelWatching.find({
user_id: user._id, user_id: user._id,
// 削除されたドキュメントは除く // 削除されたドキュメントは除く
deleted_at: { $exists: false } deleted_at: { $exists: false }
}).then(watches => watches.map(w => w.channel_id)) }).then(watches => watches.map(w => w.channel_id)),
// ミュートしているユーザーを取得
mutedUserIds: Mute.find({
muter_id: user._id,
// 削除されたドキュメントは除く
deleted_at: { $exists: false }
}).then(ms => ms.map(m => m.mutee_id))
}); });
//#region Construct query //#region Construct query
@ -77,7 +86,17 @@ module.exports = async (params, user, app) => {
channel_id: { channel_id: {
$in: watchingChannelIds $in: watchingChannelIds
} }
}] }],
// mute
user_id: {
$nin: mutedUserIds
},
'_reply.user_id': {
$nin: mutedUserIds
},
'_repost.user_id': {
$nin: mutedUserIds
},
} as any; } as any;
if (sinceId) { if (sinceId) {
@ -85,18 +104,18 @@ module.exports = async (params, user, app) => {
query._id = { query._id = {
$gt: sinceId $gt: sinceId
}; };
} else if (maxId) { } else if (untilId) {
query._id = { query._id = {
$lt: maxId $lt: untilId
}; };
} else if (sinceDate) { } else if (sinceDate) {
sort._id = 1; sort._id = 1;
query.created_at = { query.created_at = {
$gt: new Date(sinceDate) $gt: new Date(sinceDate)
}; };
} else if (maxDate) { } else if (untilDate) {
query.created_at = { query.created_at = {
$lt: new Date(maxDate) $lt: new Date(untilDate)
}; };
} }
//#endregion //#endregion
@ -109,5 +128,5 @@ module.exports = async (params, user, app) => {
}); });
// Serialize // Serialize
return await Promise.all(timeline.map(post => serialize(post, user))); return await Promise.all(timeline.map(post => pack(post, user)));
}; };

View File

@ -3,8 +3,7 @@
*/ */
const ms = require('ms'); const ms = require('ms');
import $ from 'cafy'; import $ from 'cafy';
import Post from '../../models/post'; import Post, { pack } from '../../models/post';
import serialize from '../../serializers/post';
/** /**
* Get trend posts * Get trend posts
@ -76,5 +75,5 @@ module.exports = (params, user) => new Promise(async (res, rej) => {
// Serialize // Serialize
res(await Promise.all(posts.map(async post => res(await Promise.all(posts.map(async post =>
await serialize(post, user, { detail: true })))); await pack(post, user, { detail: true }))));
}); });

View File

@ -2,8 +2,7 @@
* Module dependencies * Module dependencies
*/ */
import $ from 'cafy'; import $ from 'cafy';
import User from '../models/user'; import User, { pack } from '../models/user';
import serialize from '../serializers/user';
/** /**
* Lists all users * Lists all users
@ -21,13 +20,13 @@ module.exports = (params, me) => new Promise(async (res, rej) => {
const [sinceId, sinceIdErr] = $(params.since_id).optional.id().$; const [sinceId, sinceIdErr] = $(params.since_id).optional.id().$;
if (sinceIdErr) return rej('invalid since_id param'); if (sinceIdErr) return rej('invalid since_id param');
// Get 'max_id' parameter // Get 'until_id' parameter
const [maxId, maxIdErr] = $(params.max_id).optional.id().$; const [untilId, untilIdErr] = $(params.until_id).optional.id().$;
if (maxIdErr) return rej('invalid max_id param'); if (untilIdErr) return rej('invalid until_id param');
// Check if both of since_id and max_id is specified // Check if both of since_id and until_id is specified
if (sinceId && maxId) { if (sinceId && untilId) {
return rej('cannot set since_id and max_id'); return rej('cannot set since_id and until_id');
} }
// Construct query // Construct query
@ -40,9 +39,9 @@ module.exports = (params, me) => new Promise(async (res, rej) => {
query._id = { query._id = {
$gt: sinceId $gt: sinceId
}; };
} else if (maxId) { } else if (untilId) {
query._id = { query._id = {
$lt: maxId $lt: untilId
}; };
} }
@ -55,5 +54,5 @@ module.exports = (params, me) => new Promise(async (res, rej) => {
// Serialize // Serialize
res(await Promise.all(users.map(async user => res(await Promise.all(users.map(async user =>
await serialize(user, me)))); await pack(user, me))));
}); });

View File

@ -4,7 +4,7 @@
import $ from 'cafy'; import $ from 'cafy';
import User from '../../models/user'; import User from '../../models/user';
import Following from '../../models/following'; import Following from '../../models/following';
import serialize from '../../serializers/user'; import { pack } from '../../models/user';
import getFriends from '../../common/get-friends'; import getFriends from '../../common/get-friends';
/** /**
@ -82,7 +82,7 @@ module.exports = (params, me) => new Promise(async (res, rej) => {
// Serialize // Serialize
const users = await Promise.all(following.map(async f => const users = await Promise.all(following.map(async f =>
await serialize(f.follower_id, me, { detail: true }))); await pack(f.follower_id, me, { detail: true })));
// Response // Response
res({ res({

View File

@ -4,7 +4,7 @@
import $ from 'cafy'; import $ from 'cafy';
import User from '../../models/user'; import User from '../../models/user';
import Following from '../../models/following'; import Following from '../../models/following';
import serialize from '../../serializers/user'; import { pack } from '../../models/user';
import getFriends from '../../common/get-friends'; import getFriends from '../../common/get-friends';
/** /**
@ -82,7 +82,7 @@ module.exports = (params, me) => new Promise(async (res, rej) => {
// Serialize // Serialize
const users = await Promise.all(following.map(async f => const users = await Promise.all(following.map(async f =>
await serialize(f.followee_id, me, { detail: true }))); await pack(f.followee_id, me, { detail: true })));
// Response // Response
res({ res({

View File

@ -3,8 +3,7 @@
*/ */
import $ from 'cafy'; import $ from 'cafy';
import Post from '../../models/post'; import Post from '../../models/post';
import User from '../../models/user'; import User, { pack } from '../../models/user';
import serialize from '../../serializers/user';
module.exports = (params, me) => new Promise(async (res, rej) => { module.exports = (params, me) => new Promise(async (res, rej) => {
// Get 'user_id' parameter // Get 'user_id' parameter
@ -91,7 +90,7 @@ module.exports = (params, me) => new Promise(async (res, rej) => {
// Make replies object (includes weights) // Make replies object (includes weights)
const repliesObj = await Promise.all(topRepliedUsers.map(async (user) => ({ const repliesObj = await Promise.all(topRepliedUsers.map(async (user) => ({
user: await serialize(user, me, { detail: true }), user: await pack(user, me, { detail: true }),
weight: repliedUsers[user] / peak weight: repliedUsers[user] / peak
}))); })));

View File

@ -2,9 +2,8 @@
* Module dependencies * Module dependencies
*/ */
import $ from 'cafy'; import $ from 'cafy';
import Post from '../../models/post'; import Post, { pack } from '../../models/post';
import User from '../../models/user'; import User from '../../models/user';
import serialize from '../../serializers/post';
/** /**
* Get posts of a user * Get posts of a user
@ -42,21 +41,21 @@ module.exports = (params, me) => new Promise(async (res, rej) => {
const [sinceId, sinceIdErr] = $(params.since_id).optional.id().$; const [sinceId, sinceIdErr] = $(params.since_id).optional.id().$;
if (sinceIdErr) return rej('invalid since_id param'); if (sinceIdErr) return rej('invalid since_id param');
// Get 'max_id' parameter // Get 'until_id' parameter
const [maxId, maxIdErr] = $(params.max_id).optional.id().$; const [untilId, untilIdErr] = $(params.until_id).optional.id().$;
if (maxIdErr) return rej('invalid max_id param'); if (untilIdErr) return rej('invalid until_id param');
// Get 'since_date' parameter // Get 'since_date' parameter
const [sinceDate, sinceDateErr] = $(params.since_date).optional.number().$; const [sinceDate, sinceDateErr] = $(params.since_date).optional.number().$;
if (sinceDateErr) throw 'invalid since_date param'; if (sinceDateErr) throw 'invalid since_date param';
// Get 'max_date' parameter // Get 'until_date' parameter
const [maxDate, maxDateErr] = $(params.max_date).optional.number().$; const [untilDate, untilDateErr] = $(params.until_date).optional.number().$;
if (maxDateErr) throw 'invalid max_date param'; if (untilDateErr) throw 'invalid until_date param';
// Check if only one of since_id, max_id, since_date, max_date specified // Check if only one of since_id, until_id, since_date, until_date specified
if ([sinceId, maxId, sinceDate, maxDate].filter(x => x != null).length > 1) { if ([sinceId, untilId, sinceDate, untilDate].filter(x => x != null).length > 1) {
throw 'only one of since_id, max_id, since_date, max_date can be specified'; throw 'only one of since_id, until_id, since_date, until_date can be specified';
} }
const q = userId !== undefined const q = userId !== undefined
@ -88,18 +87,18 @@ module.exports = (params, me) => new Promise(async (res, rej) => {
query._id = { query._id = {
$gt: sinceId $gt: sinceId
}; };
} else if (maxId) { } else if (untilId) {
query._id = { query._id = {
$lt: maxId $lt: untilId
}; };
} else if (sinceDate) { } else if (sinceDate) {
sort._id = 1; sort._id = 1;
query.created_at = { query.created_at = {
$gt: new Date(sinceDate) $gt: new Date(sinceDate)
}; };
} else if (maxDate) { } else if (untilDate) {
query.created_at = { query.created_at = {
$lt: new Date(maxDate) $lt: new Date(untilDate)
}; };
} }
@ -124,6 +123,6 @@ module.exports = (params, me) => new Promise(async (res, rej) => {
// Serialize // Serialize
res(await Promise.all(posts.map(async (post) => res(await Promise.all(posts.map(async (post) =>
await serialize(post, me) await pack(post, me)
))); )));
}); });

View File

@ -3,8 +3,7 @@
*/ */
const ms = require('ms'); const ms = require('ms');
import $ from 'cafy'; import $ from 'cafy';
import User from '../../models/user'; import User, { pack } from '../../models/user';
import serialize from '../../serializers/user';
import getFriends from '../../common/get-friends'; import getFriends from '../../common/get-friends';
/** /**
@ -44,5 +43,5 @@ module.exports = (params, me) => new Promise(async (res, rej) => {
// Serialize // Serialize
res(await Promise.all(users.map(async user => res(await Promise.all(users.map(async user =>
await serialize(user, me, { detail: true })))); await pack(user, me, { detail: true }))));
}); });

View File

@ -3,8 +3,7 @@
*/ */
import * as mongo from 'mongodb'; import * as mongo from 'mongodb';
import $ from 'cafy'; import $ from 'cafy';
import User from '../../models/user'; import User, { pack } from '../../models/user';
import serialize from '../../serializers/user';
import config from '../../../conf'; import config from '../../../conf';
const escapeRegexp = require('escape-regexp'); const escapeRegexp = require('escape-regexp');
@ -52,7 +51,7 @@ async function byNative(res, rej, me, query, offset, max) {
// Serialize // Serialize
res(await Promise.all(users.map(async user => res(await Promise.all(users.map(async user =>
await serialize(user, me, { detail: true })))); await pack(user, me, { detail: true }))));
} }
// Search by Elasticsearch // Search by Elasticsearch
@ -94,6 +93,6 @@ async function byElasticsearch(res, rej, me, query, offset, max) {
// Serialize // Serialize
res(await Promise.all(users.map(async user => res(await Promise.all(users.map(async user =>
await serialize(user, me, { detail: true })))); await pack(user, me, { detail: true }))));
}); });
} }

View File

@ -2,8 +2,7 @@
* Module dependencies * Module dependencies
*/ */
import $ from 'cafy'; import $ from 'cafy';
import User from '../../models/user'; import User, { pack } from '../../models/user';
import serialize from '../../serializers/user';
/** /**
* Search a user by username * Search a user by username
@ -35,5 +34,5 @@ module.exports = (params, me) => new Promise(async (res, rej) => {
// Serialize // Serialize
res(await Promise.all(users.map(async user => res(await Promise.all(users.map(async user =>
await serialize(user, me, { detail: true })))); await pack(user, me, { detail: true }))));
}); });

View File

@ -2,8 +2,7 @@
* Module dependencies * Module dependencies
*/ */
import $ from 'cafy'; import $ from 'cafy';
import User from '../../models/user'; import User, { pack } from '../../models/user';
import serialize from '../../serializers/user';
/** /**
* Show a user * Show a user
@ -41,7 +40,7 @@ module.exports = (params, me) => new Promise(async (res, rej) => {
} }
// Send response // Send response
res(await serialize(user, me, { res(await pack(user, me, {
detail: true detail: true
})); }));
}); });

View File

@ -1,13 +1,97 @@
import * as mongo from 'mongodb';
import deepcopy = require('deepcopy');
import AccessToken from './access-token';
import db from '../../db/mongodb'; import db from '../../db/mongodb';
import config from '../../conf';
const collection = db.get('apps'); const App = db.get<IApp>('apps');
App.createIndex('name_id');
App.createIndex('name_id_lower');
App.createIndex('secret');
export default App;
(collection as any).createIndex('name_id'); // fuck type definition export type IApp = {
(collection as any).createIndex('name_id_lower'); // fuck type definition _id: mongo.ObjectID;
(collection as any).createIndex('secret'); // fuck type definition created_at: Date;
user_id: mongo.ObjectID;
export default collection as any; // fuck type definition secret: string;
};
export function isValidNameId(nameId: string): boolean { export function isValidNameId(nameId: string): boolean {
return typeof nameId == 'string' && /^[a-zA-Z0-9\-]{3,30}$/.test(nameId); return typeof nameId == 'string' && /^[a-zA-Z0-9\-]{3,30}$/.test(nameId);
} }
/**
* Pack an app for API response
*
* @param {any} app
* @param {any} me?
* @param {any} options?
* @return {Promise<any>}
*/
export const pack = (
app: any,
me?: any,
options?: {
includeSecret?: boolean,
includeProfileImageIds?: boolean
}
) => new Promise<any>(async (resolve, reject) => {
const opts = options || {
includeSecret: false,
includeProfileImageIds: false
};
let _app: any;
// Populate the app if 'app' is ID
if (mongo.ObjectID.prototype.isPrototypeOf(app)) {
_app = await App.findOne({
_id: app
});
} else if (typeof app === 'string') {
_app = await App.findOne({
_id: new mongo.ObjectID(app)
});
} else {
_app = deepcopy(app);
}
// Me
if (me && !mongo.ObjectID.prototype.isPrototypeOf(me)) {
if (typeof me === 'string') {
me = new mongo.ObjectID(me);
} else {
me = me._id;
}
}
// Rename _id to id
_app.id = _app._id;
delete _app._id;
delete _app.name_id_lower;
// Visible by only owner
if (!opts.includeSecret) {
delete _app.secret;
}
_app.icon_url = _app.icon != null
? `${config.drive_url}/${_app.icon}`
: `${config.drive_url}/app-default.jpg`;
if (me) {
// 既に連携しているか
const exist = await AccessToken.count({
app_id: _app.id,
user_id: me,
}, {
limit: 1
});
_app.is_authorized = exist === 1;
}
resolve(_app);
});

View File

@ -1,3 +1,45 @@
import * as mongo from 'mongodb';
import deepcopy = require('deepcopy');
import db from '../../db/mongodb'; import db from '../../db/mongodb';
import { pack as packApp } from './app';
export default db.get('auth_sessions') as any; // fuck type definition const AuthSession = db.get('auth_sessions');
export default AuthSession;
export interface IAuthSession {
_id: mongo.ObjectID;
}
/**
* Pack an auth session for API response
*
* @param {any} session
* @param {any} me?
* @return {Promise<any>}
*/
export const pack = (
session: any,
me?: any
) => new Promise<any>(async (resolve, reject) => {
let _session: any;
// TODO: Populate session if it ID
_session = deepcopy(session);
// Me
if (me && !mongo.ObjectID.prototype.isPrototypeOf(me)) {
if (typeof me === 'string') {
me = new mongo.ObjectID(me);
} else {
me = me._id;
}
}
delete _session._id;
// Populate app
_session.app = await packApp(_session.app_id, me);
resolve(_session);
});

View File

@ -1,9 +1,11 @@
import * as mongo from 'mongodb'; import * as mongo from 'mongodb';
import deepcopy = require('deepcopy');
import { IUser } from './user';
import Watching from './channel-watching';
import db from '../../db/mongodb'; import db from '../../db/mongodb';
const collection = db.get('channels'); const Channel = db.get<IChannel>('channels');
export default Channel;
export default collection as any; // fuck type definition
export type IChannel = { export type IChannel = {
_id: mongo.ObjectID; _id: mongo.ObjectID;
@ -12,3 +14,61 @@ export type IChannel = {
user_id: mongo.ObjectID; user_id: mongo.ObjectID;
index: number; index: number;
}; };
/**
* Pack a channel for API response
*
* @param channel target
* @param me? serializee
* @return response
*/
export const pack = (
channel: string | mongo.ObjectID | IChannel,
me?: string | mongo.ObjectID | IUser
) => new Promise<any>(async (resolve, reject) => {
let _channel: any;
// Populate the channel if 'channel' is ID
if (mongo.ObjectID.prototype.isPrototypeOf(channel)) {
_channel = await Channel.findOne({
_id: channel
});
} else if (typeof channel === 'string') {
_channel = await Channel.findOne({
_id: new mongo.ObjectID(channel)
});
} else {
_channel = deepcopy(channel);
}
// Rename _id to id
_channel.id = _channel._id;
delete _channel._id;
// Remove needless properties
delete _channel.user_id;
// Me
const meId: mongo.ObjectID = me
? mongo.ObjectID.prototype.isPrototypeOf(me)
? me as mongo.ObjectID
: typeof me === 'string'
? new mongo.ObjectID(me)
: (me as IUser)._id
: null;
if (me) {
//#region Watchしているかどうか
const watch = await Watching.findOne({
user_id: meId,
channel_id: _channel.id,
deleted_at: { $exists: false }
});
_channel.is_watching = watch !== null;
//#endregion
}
resolve(_channel);
});

View File

@ -1,9 +1,12 @@
import * as mongodb from 'mongodb'; import * as mongodb from 'mongodb';
import deepcopy = require('deepcopy');
import { pack as packFolder } from './drive-folder';
import config from '../../conf';
import monkDb, { nativeDbConn } from '../../db/mongodb'; import monkDb, { nativeDbConn } from '../../db/mongodb';
const collection = monkDb.get('drive_files.files'); const DriveFile = monkDb.get<IDriveFile>('drive_files.files');
export default collection as any; // fuck type definition export default DriveFile;
const getGridFSBucket = async (): Promise<mongodb.GridFSBucket> => { const getGridFSBucket = async (): Promise<mongodb.GridFSBucket> => {
const db = await nativeDbConn(); const db = await nativeDbConn();
@ -15,6 +18,19 @@ const getGridFSBucket = async (): Promise<mongodb.GridFSBucket> => {
export { getGridFSBucket }; export { getGridFSBucket };
export type IDriveFile = {
_id: mongodb.ObjectID;
uploadDate: Date;
md5: string;
filename: string;
contentType: string;
metadata: {
properties: any;
user_id: mongodb.ObjectID;
folder_id: mongodb.ObjectID;
}
};
export function validateFileName(name: string): boolean { export function validateFileName(name: string): boolean {
return ( return (
(name.trim().length > 0) && (name.trim().length > 0) &&
@ -24,3 +40,74 @@ export function validateFileName(name: string): boolean {
(name.indexOf('..') === -1) (name.indexOf('..') === -1)
); );
} }
/**
* Pack a drive file for API response
*
* @param {any} file
* @param {any} options?
* @return {Promise<any>}
*/
export const pack = (
file: any,
options?: {
detail: boolean
}
) => new Promise<any>(async (resolve, reject) => {
const opts = Object.assign({
detail: false
}, options);
let _file: any;
// Populate the file if 'file' is ID
if (mongodb.ObjectID.prototype.isPrototypeOf(file)) {
_file = await DriveFile.findOne({
_id: file
});
} else if (typeof file === 'string') {
_file = await DriveFile.findOne({
_id: new mongodb.ObjectID(file)
});
} else {
_file = deepcopy(file);
}
if (!_file) return reject('invalid file arg.');
// rendered target
let _target: any = {};
_target.id = _file._id;
_target.created_at = _file.uploadDate;
_target.name = _file.filename;
_target.type = _file.contentType;
_target.datasize = _file.length;
_target.md5 = _file.md5;
_target = Object.assign(_target, _file.metadata);
_target.url = `${config.drive_url}/${_target.id}/${encodeURIComponent(_target.name)}`;
if (_target.properties == null) _target.properties = {};
if (opts.detail) {
if (_target.folder_id) {
// Populate folder
_target.folder = await packFolder(_target.folder_id, {
detail: true
});
}
/*
if (_target.tags) {
// Populate tags
_target.tags = await _target.tags.map(async (tag: any) =>
await serializeDriveTag(tag)
);
}
*/
}
resolve(_target);
});

View File

@ -1,6 +1,18 @@
import * as mongo from 'mongodb';
import deepcopy = require('deepcopy');
import db from '../../db/mongodb'; import db from '../../db/mongodb';
import DriveFile from './drive-file';
export default db.get('drive_folders') as any; // fuck type definition const DriveFolder = db.get<IDriveFolder>('drive_folders');
export default DriveFolder;
export type IDriveFolder = {
_id: mongo.ObjectID;
created_at: Date;
name: string;
user_id: mongo.ObjectID;
parent_id: mongo.ObjectID;
};
export function isValidFolderName(name: string): boolean { export function isValidFolderName(name: string): boolean {
return ( return (
@ -8,3 +20,58 @@ export function isValidFolderName(name: string): boolean {
(name.length <= 200) (name.length <= 200)
); );
} }
/**
* Pack a drive folder for API response
*
* @param {any} folder
* @param {any} options?
* @return {Promise<any>}
*/
export const pack = (
folder: any,
options?: {
detail: boolean
}
) => new Promise<any>(async (resolve, reject) => {
const opts = Object.assign({
detail: false
}, options);
let _folder: any;
// Populate the folder if 'folder' is ID
if (mongo.ObjectID.prototype.isPrototypeOf(folder)) {
_folder = await DriveFolder.findOne({ _id: folder });
} else if (typeof folder === 'string') {
_folder = await DriveFolder.findOne({ _id: new mongo.ObjectID(folder) });
} else {
_folder = deepcopy(folder);
}
// Rename _id to id
_folder.id = _folder._id;
delete _folder._id;
if (opts.detail) {
const childFoldersCount = await DriveFolder.count({
parent_id: _folder.id
});
const childFilesCount = await DriveFile.count({
'metadata.folder_id': _folder.id
});
_folder.folders_count = childFoldersCount;
_folder.files_count = childFilesCount;
}
if (opts.detail && _folder.parent_id) {
// Populate parent folder
_folder.parent = await pack(_folder.parent_id, {
detail: true
});
}
resolve(_folder);
});

View File

@ -1,12 +1,81 @@
import * as mongo from 'mongodb'; import * as mongo from 'mongodb';
import deepcopy = require('deepcopy');
import { pack as packUser } from './user';
import { pack as packFile } from './drive-file';
import db from '../../db/mongodb'; import db from '../../db/mongodb';
import parse from '../common/text';
export default db.get('messaging_messages') as any; // fuck type definition const MessagingMessage = db.get<IMessagingMessage>('messaging_messages');
export default MessagingMessage;
export interface IMessagingMessage { export interface IMessagingMessage {
_id: mongo.ObjectID; _id: mongo.ObjectID;
created_at: Date;
text: string;
user_id: mongo.ObjectID;
recipient_id: mongo.ObjectID;
is_read: boolean;
} }
export function isValidText(text: string): boolean { export function isValidText(text: string): boolean {
return text.length <= 1000 && text.trim() != ''; return text.length <= 1000 && text.trim() != '';
} }
/**
* Pack a messaging message for API response
*
* @param {any} message
* @param {any} me?
* @param {any} options?
* @return {Promise<any>}
*/
export const pack = (
message: any,
me?: any,
options?: {
populateRecipient: boolean
}
) => new Promise<any>(async (resolve, reject) => {
const opts = options || {
populateRecipient: true
};
let _message: any;
// Populate the message if 'message' is ID
if (mongo.ObjectID.prototype.isPrototypeOf(message)) {
_message = await MessagingMessage.findOne({
_id: message
});
} else if (typeof message === 'string') {
_message = await MessagingMessage.findOne({
_id: new mongo.ObjectID(message)
});
} else {
_message = deepcopy(message);
}
// Rename _id to id
_message.id = _message._id;
delete _message._id;
// Parse text
if (_message.text) {
_message.ast = parse(_message.text);
}
// Populate user
_message.user = await packUser(_message.user_id, me);
if (_message.file) {
// Populate file
_message.file = await packFile(_message.file_id);
}
if (opts.populateRecipient) {
// Populate recipient
_message.recipient = await packUser(_message.recipient_id, me);
}
resolve(_message);
});

3
src/api/models/mute.ts Normal file
View File

@ -0,0 +1,3 @@
import db from '../../db/mongodb';
export default db.get('mute') as any; // fuck type definition

View File

@ -1,8 +1,11 @@
import * as mongo from 'mongodb'; import * as mongo from 'mongodb';
import deepcopy = require('deepcopy');
import db from '../../db/mongodb'; import db from '../../db/mongodb';
import { IUser } from './user'; import { IUser, pack as packUser } from './user';
import { pack as packPost } from './post';
export default db.get('notifications') as any; // fuck type definition const Notification = db.get<INotification>('notifications');
export default Notification;
export interface INotification { export interface INotification {
_id: mongo.ObjectID; _id: mongo.ObjectID;
@ -45,3 +48,60 @@ export interface INotification {
*/ */
is_read: Boolean; is_read: Boolean;
} }
/**
* Pack a notification for API response
*
* @param {any} notification
* @return {Promise<any>}
*/
export const pack = (notification: any) => new Promise<any>(async (resolve, reject) => {
let _notification: any;
// Populate the notification if 'notification' is ID
if (mongo.ObjectID.prototype.isPrototypeOf(notification)) {
_notification = await Notification.findOne({
_id: notification
});
} else if (typeof notification === 'string') {
_notification = await Notification.findOne({
_id: new mongo.ObjectID(notification)
});
} else {
_notification = deepcopy(notification);
}
// Rename _id to id
_notification.id = _notification._id;
delete _notification._id;
// Rename notifier_id to user_id
_notification.user_id = _notification.notifier_id;
delete _notification.notifier_id;
const me = _notification.notifiee_id;
delete _notification.notifiee_id;
// Populate notifier
_notification.user = await packUser(_notification.user_id, me);
switch (_notification.type) {
case 'follow':
// nope
break;
case 'mention':
case 'reply':
case 'repost':
case 'quote':
case 'reaction':
case 'poll_vote':
// Populate post
_notification.post = await packPost(_notification.post_id, me);
break;
default:
console.error(`Unknown type: ${_notification.type}`);
break;
}
resolve(_notification);
});

View File

@ -1,3 +1,51 @@
import * as mongo from 'mongodb';
import deepcopy = require('deepcopy');
import db from '../../db/mongodb'; import db from '../../db/mongodb';
import Reaction from './post-reaction';
import { pack as packUser } from './user';
export default db.get('post_reactions') as any; // fuck type definition const PostReaction = db.get<IPostReaction>('post_reactions');
export default PostReaction;
export interface IPostReaction {
_id: mongo.ObjectID;
created_at: Date;
deleted_at: Date;
reaction: string;
}
/**
* Pack a reaction for API response
*
* @param {any} reaction
* @param {any} me?
* @return {Promise<any>}
*/
export const pack = (
reaction: any,
me?: any
) => new Promise<any>(async (resolve, reject) => {
let _reaction: any;
// Populate the reaction if 'reaction' is ID
if (mongo.ObjectID.prototype.isPrototypeOf(reaction)) {
_reaction = await Reaction.findOne({
_id: reaction
});
} else if (typeof reaction === 'string') {
_reaction = await Reaction.findOne({
_id: new mongo.ObjectID(reaction)
});
} else {
_reaction = deepcopy(reaction);
}
// Rename _id to id
_reaction.id = _reaction._id;
delete _reaction._id;
// Populate user
_reaction.user = await packUser(_reaction.user_id, me);
resolve(_reaction);
});

View File

@ -1,8 +1,18 @@
import * as mongo from 'mongodb'; import * as mongo from 'mongodb';
import deepcopy = require('deepcopy');
import rap from '@prezzemolo/rap';
import db from '../../db/mongodb'; import db from '../../db/mongodb';
import { IUser, pack as packUser } from './user';
import { pack as packApp } from './app';
import { pack as packChannel } from './channel';
import Vote from './poll-vote';
import Reaction from './post-reaction';
import { pack as packFile } from './drive-file';
import parse from '../common/text';
export default db.get('posts') as any; // fuck type definition const Post = db.get<IPost>('posts');
export default Post;
export function isValidText(text: string): boolean { export function isValidText(text: string): boolean {
return text.length <= 1000 && text.trim() != ''; return text.length <= 1000 && text.trim() != '';
@ -15,8 +25,185 @@ export type IPost = {
media_ids: mongo.ObjectID[]; media_ids: mongo.ObjectID[];
reply_id: mongo.ObjectID; reply_id: mongo.ObjectID;
repost_id: mongo.ObjectID; repost_id: mongo.ObjectID;
poll: {}; // todo poll: any; // todo
text: string; text: string;
user_id: mongo.ObjectID; user_id: mongo.ObjectID;
app_id: mongo.ObjectID; app_id: mongo.ObjectID;
category: string;
is_category_verified: boolean;
};
/**
* Pack a post for API response
*
* @param post target
* @param me? serializee
* @param options? serialize options
* @return response
*/
export const pack = async (
post: string | mongo.ObjectID | IPost,
me?: string | mongo.ObjectID | IUser,
options?: {
detail: boolean
}
) => {
const opts = options || {
detail: true,
};
// Me
const meId: mongo.ObjectID = me
? mongo.ObjectID.prototype.isPrototypeOf(me)
? me as mongo.ObjectID
: typeof me === 'string'
? new mongo.ObjectID(me)
: (me as IUser)._id
: null;
let _post: any;
// Populate the post if 'post' is ID
if (mongo.ObjectID.prototype.isPrototypeOf(post)) {
_post = await Post.findOne({
_id: post
});
} else if (typeof post === 'string') {
_post = await Post.findOne({
_id: new mongo.ObjectID(post)
});
} else {
_post = deepcopy(post);
}
if (!_post) throw 'invalid post arg.';
const id = _post._id;
// Rename _id to id
_post.id = _post._id;
delete _post._id;
delete _post.mentions;
// Parse text
if (_post.text) {
_post.ast = parse(_post.text);
}
// Populate user
_post.user = packUser(_post.user_id, meId);
// Populate app
if (_post.app_id) {
_post.app = packApp(_post.app_id);
}
// Populate channel
if (_post.channel_id) {
_post.channel = packChannel(_post.channel_id);
}
// Populate media
if (_post.media_ids) {
_post.media = Promise.all(_post.media_ids.map(fileId =>
packFile(fileId)
));
}
// When requested a detailed post data
if (opts.detail) {
// Get previous post info
_post.prev = (async () => {
const prev = await Post.findOne({
user_id: _post.user_id,
_id: {
$lt: id
}
}, {
fields: {
_id: true
},
sort: {
_id: -1
}
});
return prev ? prev._id : null;
})();
// Get next post info
_post.next = (async () => {
const next = await Post.findOne({
user_id: _post.user_id,
_id: {
$gt: id
}
}, {
fields: {
_id: true
},
sort: {
_id: 1
}
});
return next ? next._id : null;
})();
if (_post.reply_id) {
// Populate reply to post
_post.reply = pack(_post.reply_id, meId, {
detail: false
});
}
if (_post.repost_id) {
// Populate repost
_post.repost = pack(_post.repost_id, meId, {
detail: _post.text == null
});
}
// Poll
if (meId && _post.poll) {
_post.poll = (async (poll) => {
const vote = await Vote
.findOne({
user_id: meId,
post_id: id
});
if (vote != null) {
const myChoice = poll.choices
.filter(c => c.id == vote.choice)[0];
myChoice.is_voted = true;
}
return poll;
})(_post.poll);
}
// Fetch my reaction
if (meId) {
_post.my_reaction = (async () => {
const reaction = await Reaction
.findOne({
user_id: meId,
post_id: id,
deleted_at: { $exists: false }
});
if (reaction) {
return reaction.reaction;
}
return null;
})();
}
}
// resolve promises in _post object
_post = await rap(_post);
return _post;
}; };

View File

@ -1,3 +1,29 @@
import * as mongo from 'mongodb';
import deepcopy = require('deepcopy');
import db from '../../db/mongodb'; import db from '../../db/mongodb';
export default db.get('signin') as any; // fuck type definition const Signin = db.get<ISignin>('signin');
export default Signin;
export interface ISignin {
_id: mongo.ObjectID;
}
/**
* Pack a signin record for API response
*
* @param {any} record
* @return {Promise<any>}
*/
export const pack = (
record: any
) => new Promise<any>(async (resolve, reject) => {
const _record = deepcopy(record);
// Rename _id to id
_record.id = _record._id;
delete _record._id;
resolve(_record);
});

View File

@ -1,14 +1,19 @@
import * as mongo from 'mongodb'; import * as mongo from 'mongodb';
import deepcopy = require('deepcopy');
import rap from '@prezzemolo/rap';
import db from '../../db/mongodb'; import db from '../../db/mongodb';
import { IPost } from './post'; import { IPost, pack as packPost } from './post';
import Following from './following';
import Mute from './mute';
import getFriends from '../common/get-friends';
import config from '../../conf';
const collection = db.get('users'); const User = db.get<IUser>('users');
(collection as any).createIndex('username'); // fuck type definition User.createIndex('username');
(collection as any).createIndex('token'); // fuck type definition User.createIndex('token');
export default collection as any; // fuck type definition export default User;
export function validateUsername(username: string): boolean { export function validateUsername(username: string): boolean {
return typeof username == 'string' && /^[a-zA-Z0-9\-]{3,20}$/.test(username); return typeof username == 'string' && /^[a-zA-Z0-9\-]{3,20}$/.test(username);
@ -37,6 +42,7 @@ export function isValidBirthday(birthday: string): boolean {
export type IUser = { export type IUser = {
_id: mongo.ObjectID; _id: mongo.ObjectID;
created_at: Date; created_at: Date;
deleted_at: Date;
email: string; email: string;
followers_count: number; followers_count: number;
following_count: number; following_count: number;
@ -72,6 +78,8 @@ export type IUser = {
is_pro: boolean; is_pro: boolean;
is_suspended: boolean; is_suspended: boolean;
keywords: string[]; keywords: string[];
two_factor_secret: string;
two_factor_enabled: boolean;
}; };
export function init(user): IUser { export function init(user): IUser {
@ -81,3 +89,182 @@ export function init(user): IUser {
user.pinned_post_id = new mongo.ObjectID(user.pinned_post_id); user.pinned_post_id = new mongo.ObjectID(user.pinned_post_id);
return user; return user;
} }
/**
* Pack a user for API response
*
* @param user target
* @param me? serializee
* @param options? serialize options
* @return Packed user
*/
export const pack = (
user: string | mongo.ObjectID | IUser,
me?: string | mongo.ObjectID | IUser,
options?: {
detail?: boolean,
includeSecrets?: boolean
}
) => new Promise<any>(async (resolve, reject) => {
const opts = Object.assign({
detail: false,
includeSecrets: false
}, options);
let _user: any;
const fields = opts.detail ? {
settings: false
} : {
settings: false,
client_settings: false,
profile: false,
keywords: false,
domains: false
};
// Populate the user if 'user' is ID
if (mongo.ObjectID.prototype.isPrototypeOf(user)) {
_user = await User.findOne({
_id: user
}, { fields });
} else if (typeof user === 'string') {
_user = await User.findOne({
_id: new mongo.ObjectID(user)
}, { fields });
} else {
_user = deepcopy(user);
}
if (!_user) return reject('invalid user arg.');
// Me
const meId: mongo.ObjectID = me
? mongo.ObjectID.prototype.isPrototypeOf(me)
? me as mongo.ObjectID
: typeof me === 'string'
? new mongo.ObjectID(me)
: (me as IUser)._id
: null;
// Rename _id to id
_user.id = _user._id;
delete _user._id;
// Remove needless properties
delete _user.latest_post;
// Remove private properties
delete _user.password;
delete _user.token;
delete _user.two_factor_temp_secret;
delete _user.two_factor_secret;
delete _user.username_lower;
if (_user.twitter) {
delete _user.twitter.access_token;
delete _user.twitter.access_token_secret;
}
delete _user.line;
// Visible via only the official client
if (!opts.includeSecrets) {
delete _user.email;
delete _user.client_settings;
}
if (!opts.detail) {
delete _user.two_factor_enabled;
}
_user.avatar_url = _user.avatar_id != null
? `${config.drive_url}/${_user.avatar_id}`
: `${config.drive_url}/default-avatar.jpg`;
_user.banner_url = _user.banner_id != null
? `${config.drive_url}/${_user.banner_id}`
: null;
if (!meId || !meId.equals(_user.id) || !opts.detail) {
delete _user.avatar_id;
delete _user.banner_id;
delete _user.drive_capacity;
}
if (meId && !meId.equals(_user.id)) {
// Whether the user is following
_user.is_following = (async () => {
const follow = await Following.findOne({
follower_id: meId,
followee_id: _user.id,
deleted_at: { $exists: false }
});
return follow !== null;
})();
// Whether the user is followed
_user.is_followed = (async () => {
const follow2 = await Following.findOne({
follower_id: _user.id,
followee_id: meId,
deleted_at: { $exists: false }
});
return follow2 !== null;
})();
// Whether the user is muted
_user.is_muted = (async () => {
const mute = await Mute.findOne({
muter_id: meId,
mutee_id: _user.id,
deleted_at: { $exists: false }
});
return mute !== null;
})();
}
if (opts.detail) {
if (_user.pinned_post_id) {
// Populate pinned post
_user.pinned_post = packPost(_user.pinned_post_id, meId, {
detail: true
});
}
if (meId && !meId.equals(_user.id)) {
const myFollowingIds = await getFriends(meId);
// Get following you know count
_user.following_you_know_count = Following.count({
followee_id: { $in: myFollowingIds },
follower_id: _user.id,
deleted_at: { $exists: false }
});
// Get followers you know count
_user.followers_you_know_count = Following.count({
followee_id: _user.id,
follower_id: { $in: myFollowingIds },
deleted_at: { $exists: false }
});
}
}
// resolve promises in _user object
_user = await rap(_user);
resolve(_user);
});
/*
function img(url) {
return {
thumbnail: {
large: `${url}`,
medium: '',
small: ''
}
};
}
*/

View File

@ -1,16 +1,19 @@
import * as express from 'express'; import * as express from 'express';
import * as bcrypt from 'bcryptjs'; import * as bcrypt from 'bcryptjs';
import * as speakeasy from 'speakeasy';
import { default as User, IUser } from '../models/user'; import { default as User, IUser } from '../models/user';
import Signin from '../models/signin'; import Signin, { pack } from '../models/signin';
import serialize from '../serializers/signin';
import event from '../event'; import event from '../event';
import signin from '../common/signin'; import signin from '../common/signin';
import config from '../../conf';
export default async (req: express.Request, res: express.Response) => { export default async (req: express.Request, res: express.Response) => {
res.header('Access-Control-Allow-Origin', config.url);
res.header('Access-Control-Allow-Credentials', 'true'); res.header('Access-Control-Allow-Credentials', 'true');
const username = req.body['username']; const username = req.body['username'];
const password = req.body['password']; const password = req.body['password'];
const token = req.body['token'];
if (typeof username != 'string') { if (typeof username != 'string') {
res.sendStatus(400); res.sendStatus(400);
@ -22,6 +25,11 @@ export default async (req: express.Request, res: express.Response) => {
return; return;
} }
if (token != null && typeof token != 'string') {
res.sendStatus(400);
return;
}
// Fetch user // Fetch user
const user: IUser = await User.findOne({ const user: IUser = await User.findOne({
username_lower: username.toLowerCase() username_lower: username.toLowerCase()
@ -43,7 +51,23 @@ export default async (req: express.Request, res: express.Response) => {
const same = await bcrypt.compare(password, user.password); const same = await bcrypt.compare(password, user.password);
if (same) { if (same) {
signin(res, user, false); if (user.two_factor_enabled) {
const verified = (speakeasy as any).totp.verify({
secret: user.two_factor_secret,
encoding: 'base32',
token: token
});
if (verified) {
signin(res, user, false);
} else {
res.status(400).send({
error: 'invalid token'
});
}
} else {
signin(res, user, false);
}
} else { } else {
res.status(400).send({ res.status(400).send({
error: 'incorrect password' error: 'incorrect password'
@ -60,5 +84,5 @@ export default async (req: express.Request, res: express.Response) => {
}); });
// Publish signin event // Publish signin event
event(user._id, 'signin', await serialize(record)); event(user._id, 'signin', await pack(record));
}; };

View File

@ -2,9 +2,7 @@ import * as uuid from 'uuid';
import * as express from 'express'; import * as express from 'express';
import * as bcrypt from 'bcryptjs'; import * as bcrypt from 'bcryptjs';
import recaptcha = require('recaptcha-promise'); import recaptcha = require('recaptcha-promise');
import { default as User, IUser } from '../models/user'; import User, { IUser, validateUsername, validatePassword, pack } from '../models/user';
import { validateUsername, validatePassword } from '../models/user';
import serialize from '../serializers/user';
import generateUserToken from '../common/generate-native-user-token'; import generateUserToken from '../common/generate-native-user-token';
import config from '../../conf'; import config from '../../conf';
@ -142,7 +140,7 @@ export default async (req: express.Request, res: express.Response) => {
}); });
// Response // Response
res.send(await serialize(account)); res.send(await pack(account));
// Create search index // Create search index
if (config.elasticsearch.enable) { if (config.elasticsearch.enable) {

View File

@ -1,83 +0,0 @@
/**
* Module dependencies
*/
import * as mongo from 'mongodb';
import deepcopy = require('deepcopy');
import App from '../models/app';
import AccessToken from '../models/access-token';
import config from '../../conf';
/**
* Serialize an app
*
* @param {any} app
* @param {any} me?
* @param {any} options?
* @return {Promise<any>}
*/
export default (
app: any,
me?: any,
options?: {
includeSecret?: boolean,
includeProfileImageIds?: boolean
}
) => new Promise<any>(async (resolve, reject) => {
const opts = options || {
includeSecret: false,
includeProfileImageIds: false
};
let _app: any;
// Populate the app if 'app' is ID
if (mongo.ObjectID.prototype.isPrototypeOf(app)) {
_app = await App.findOne({
_id: app
});
} else if (typeof app === 'string') {
_app = await App.findOne({
_id: new mongo.ObjectID(app)
});
} else {
_app = deepcopy(app);
}
// Me
if (me && !mongo.ObjectID.prototype.isPrototypeOf(me)) {
if (typeof me === 'string') {
me = new mongo.ObjectID(me);
} else {
me = me._id;
}
}
// Rename _id to id
_app.id = _app._id;
delete _app._id;
delete _app.name_id_lower;
// Visible by only owner
if (!opts.includeSecret) {
delete _app.secret;
}
_app.icon_url = _app.icon != null
? `${config.drive_url}/${_app.icon}`
: `${config.drive_url}/app-default.jpg`;
if (me) {
// 既に連携しているか
const exist = await AccessToken.count({
app_id: _app.id,
user_id: me,
}, {
limit: 1
});
_app.is_authorized = exist === 1;
}
resolve(_app);
});

View File

@ -1,40 +0,0 @@
/**
* Module dependencies
*/
import * as mongo from 'mongodb';
import deepcopy = require('deepcopy');
import serializeApp from './app';
/**
* Serialize an auth session
*
* @param {any} session
* @param {any} me?
* @return {Promise<any>}
*/
export default (
session: any,
me?: any
) => new Promise<any>(async (resolve, reject) => {
let _session: any;
// TODO: Populate session if it ID
_session = deepcopy(session);
// Me
if (me && !mongo.ObjectID.prototype.isPrototypeOf(me)) {
if (typeof me === 'string') {
me = new mongo.ObjectID(me);
} else {
me = me._id;
}
}
delete _session._id;
// Populate app
_session.app = await serializeApp(_session.app_id, me);
resolve(_session);
});

View File

@ -1,66 +0,0 @@
/**
* Module dependencies
*/
import * as mongo from 'mongodb';
import deepcopy = require('deepcopy');
import { IUser } from '../models/user';
import { default as Channel, IChannel } from '../models/channel';
import Watching from '../models/channel-watching';
/**
* Serialize a channel
*
* @param channel target
* @param me? serializee
* @return response
*/
export default (
channel: string | mongo.ObjectID | IChannel,
me?: string | mongo.ObjectID | IUser
) => new Promise<any>(async (resolve, reject) => {
let _channel: any;
// Populate the channel if 'channel' is ID
if (mongo.ObjectID.prototype.isPrototypeOf(channel)) {
_channel = await Channel.findOne({
_id: channel
});
} else if (typeof channel === 'string') {
_channel = await Channel.findOne({
_id: new mongo.ObjectID(channel)
});
} else {
_channel = deepcopy(channel);
}
// Rename _id to id
_channel.id = _channel._id;
delete _channel._id;
// Remove needless properties
delete _channel.user_id;
// Me
const meId: mongo.ObjectID = me
? mongo.ObjectID.prototype.isPrototypeOf(me)
? me as mongo.ObjectID
: typeof me === 'string'
? new mongo.ObjectID(me)
: (me as IUser)._id
: null;
if (me) {
//#region Watchしているかどうか
const watch = await Watching.findOne({
user_id: meId,
channel_id: _channel.id,
deleted_at: { $exists: false }
});
_channel.is_watching = watch !== null;
//#endregion
}
resolve(_channel);
});

View File

@ -1,74 +0,0 @@
/**
* Module dependencies
*/
import * as mongo from 'mongodb';
import DriveFile from '../models/drive-file';
import serializeDriveFolder from './drive-folder';
import serializeDriveTag from './drive-tag';
import deepcopy = require('deepcopy');
import config from '../../conf';
/**
* Serialize a drive file
*
* @param {any} file
* @param {any} options?
* @return {Promise<any>}
*/
export default (
file: any,
options?: {
detail: boolean
}
) => new Promise<any>(async (resolve, reject) => {
const opts = Object.assign({
detail: false
}, options);
let _file: any;
// Populate the file if 'file' is ID
if (mongo.ObjectID.prototype.isPrototypeOf(file)) {
_file = await DriveFile.findOne({
_id: file
});
} else if (typeof file === 'string') {
_file = await DriveFile.findOne({
_id: new mongo.ObjectID(file)
});
} else {
_file = deepcopy(file);
}
if (!_file) return reject('invalid file arg.');
// rendered target
let _target: any = {};
_target.id = _file._id;
_target.created_at = _file.uploadDate;
_target.name = _file.filename;
_target.type = _file.contentType;
_target.datasize = _file.length;
_target.md5 = _file.md5;
_target = Object.assign(_target, _file.metadata);
_target.url = `${config.drive_url}/${_target.id}/${encodeURIComponent(_target.name)}`;
if (opts.detail && _target.folder_id) {
// Populate folder
_target.folder = await serializeDriveFolder(_target.folder_id, {
detail: true
});
}
if (opts.detail && _target.tags) {
// Populate tags
_target.tags = await _target.tags.map(async (tag: any) =>
await serializeDriveTag(tag)
);
}
resolve(_target);
});

View File

@ -1,64 +0,0 @@
/**
* Module dependencies
*/
import * as mongo from 'mongodb';
import DriveFolder from '../models/drive-folder';
import DriveFile from '../models/drive-file';
import deepcopy = require('deepcopy');
/**
* Serialize a drive folder
*
* @param {any} folder
* @param {any} options?
* @return {Promise<any>}
*/
const self = (
folder: any,
options?: {
detail: boolean
}
) => new Promise<any>(async (resolve, reject) => {
const opts = Object.assign({
detail: false
}, options);
let _folder: any;
// Populate the folder if 'folder' is ID
if (mongo.ObjectID.prototype.isPrototypeOf(folder)) {
_folder = await DriveFolder.findOne({ _id: folder });
} else if (typeof folder === 'string') {
_folder = await DriveFolder.findOne({ _id: new mongo.ObjectID(folder) });
} else {
_folder = deepcopy(folder);
}
// Rename _id to id
_folder.id = _folder._id;
delete _folder._id;
if (opts.detail) {
const childFoldersCount = await DriveFolder.count({
parent_id: _folder.id
});
const childFilesCount = await DriveFile.count({
'metadata.folder_id': _folder.id
});
_folder.folders_count = childFoldersCount;
_folder.files_count = childFilesCount;
}
if (opts.detail && _folder.parent_id) {
// Populate parent folder
_folder.parent = await self(_folder.parent_id, {
detail: true
});
}
resolve(_folder);
});
export default self;

Some files were not shown because too many files have changed in this diff Show More