Revert "Release 20200823.1100"

This commit is contained in:
shibafu 2020-08-23 12:28:21 +09:00 committed by GitHub
parent f377b143d2
commit 1b5f690f4e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
71 changed files with 1200 additions and 4372 deletions

View File

@ -11,7 +11,7 @@ insert_final_newline = true
[*.md]
trim_trailing_whitespace = false
[*.{yml,yaml}]
[*.yml]
indent_size = 2
[*.json]

18
.eslintrc.js vendored
View File

@ -6,33 +6,25 @@ module.exports = {
},
extends: [
'eslint:recommended',
'plugin:react/recommended',
'plugin:vue/essential',
'plugin:prettier/recommended',
'plugin:@typescript-eslint/recommended',
'prettier',
'prettier/@typescript-eslint',
'prettier/react',
'prettier/vue',
],
parser: '@typescript-eslint/parser',
parser: 'vue-eslint-parser',
parserOptions: {
ecmaVersion: 11,
ecmaFeatures: {
jsx: true,
},
parser: '@typescript-eslint/parser',
sourceType: 'module',
},
plugins: ['prettier', 'react', '@typescript-eslint', 'jquery'],
plugins: ['prettier', 'vue', '@typescript-eslint', 'jquery'],
rules: {
'@typescript-eslint/explicit-module-boundary-types': 0,
'@typescript-eslint/no-explicit-any': 0,
'@typescript-eslint/no-unused-vars': ['warn', { argsIgnorePattern: '^_' }],
'jquery/no-ajax': 2,
'jquery/no-ajax-events': 2,
'react/prop-types': 0,
},
settings: {
react: {
version: 'detect',
},
},
};

1
.gitignore vendored
View File

@ -6,7 +6,6 @@
/public/storage
/public/mix-manifest.json
/public/report.html
/public/apidoc.html
/storage/*.key
/vendor
/.idea

View File

@ -1,39 +0,0 @@
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Str;
class CheckinWebhook extends Model
{
use SoftDeletes;
/** @var int ユーザーごとの作成数制限 */
const PER_USER_LIMIT = 10;
public $incrementing = false;
protected $keyType = 'string';
protected $fillable = ['name'];
protected static function boot()
{
parent::boot();
self::creating(function (CheckinWebhook $webhook) {
$webhook->id = Str::random(64);
});
}
public function user()
{
return $this->belongsTo(User::class);
}
public function isAvailable()
{
return $this->user !== null;
}
}

View File

@ -1,24 +0,0 @@
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class ContentProvider extends Model
{
public $incrementing = false;
protected $primaryKey = 'host';
protected $keyType = 'string';
protected $fillable = [
'host',
'robots',
'robots_cached_at',
];
protected $dates = [
'created_at',
'updated_at',
'robots_cached_at',
];
}

View File

@ -14,13 +14,11 @@ class Ejaculation extends Model
const SOURCE_WEB = 'web';
const SOURCE_CSV = 'csv';
const SOURCE_WEBHOOK = 'webhook';
protected $fillable = [
'user_id', 'ejaculated_date',
'note', 'geo_latitude', 'geo_longitude', 'link', 'source',
'is_private', 'is_too_sensitive',
'checkin_webhook_id'
'is_private', 'is_too_sensitive'
];
protected $dates = [
@ -49,9 +47,9 @@ class Ejaculation extends Model
return $this->hasMany(Like::class);
}
public function scopeVisibleToTimeline(Builder $query)
public function scopeOnlyWebCheckin(Builder $query)
{
return $query->whereIn('ejaculations.source', [Ejaculation::SOURCE_WEB, Ejaculation::SOURCE_WEBHOOK]);
return $query->where('ejaculations.source', Ejaculation::SOURCE_WEB);
}
public function scopeWithLikes(Builder $query)

View File

@ -4,10 +4,7 @@ namespace App\Exceptions;
use Exception;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Http\JsonResponse;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
class Handler extends ExceptionHandler
{
@ -23,7 +20,6 @@ class Handler extends ExceptionHandler
\Illuminate\Database\Eloquent\ModelNotFoundException::class,
\Illuminate\Session\TokenMismatchException::class,
\Illuminate\Validation\ValidationException::class,
\App\MetadataResolver\ResolverCircuitBreakException::class,
];
/**
@ -72,28 +68,4 @@ class Handler extends ExceptionHandler
return redirect()->guest(route('login'));
}
protected function prepareException(Exception $e)
{
if (!config('app.debug') && $e instanceof ModelNotFoundException) {
return new NotFoundHttpException('Resource not found.', $e);
}
return parent::prepareException($e);
}
protected function prepareJsonResponse($request, Exception $e)
{
$status = $this->isHttpException($e) ? $e->getStatusCode() : 500;
return new JsonResponse(
[
'status' => $status,
'error' => $this->convertExceptionToArray($e),
],
$status,
$this->isHttpException($e) ? $e->getHeaders() : [],
JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES
);
}
}

View File

@ -1,103 +0,0 @@
<?php
namespace App\Http\Controllers\Api;
use App\CheckinWebhook;
use App\Ejaculation;
use App\Events\LinkDiscovered;
use App\Http\Controllers\Controller;
use App\Http\Resources\EjaculationResource;
use App\Tag;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\ValidationException;
class WebhookController extends Controller
{
public function checkin(CheckinWebhook $webhook, Request $request)
{
if (!$webhook->isAvailable()) {
return response()->json([
'status' => 404,
'error' => [
'message' => 'The webhook is unavailable'
]
], 404);
}
$validator = Validator::make($request->all(), [
'checked_in_at' => 'nullable|date|after_or_equal:2000-01-01 00:00:00|before_or_equal:2099-12-31 23:59:59',
'note' => 'nullable|string|max:500',
'link' => 'nullable|url|max:2000',
'tags' => 'nullable|array',
'tags.*' => ['string', 'not_regex:/[\s\r\n]/u', 'max:255'],
'is_private' => 'nullable|boolean',
'is_too_sensitive' => 'nullable|boolean',
], [
'tags.*.not_regex' => 'The :attribute cannot contain spaces, tabs and newlines.'
]);
try {
$inputs = $validator->validate();
} catch (ValidationException $e) {
return response()->json([
'status' => 422,
'error' => [
'message' => 'Validation failed',
'violations' => $validator->errors()->all(),
]
], 422);
}
$ejaculatedDate = empty($inputs['checked_in_at']) ? now() : new Carbon($inputs['checked_in_at']);
$ejaculatedDate = $ejaculatedDate->setTimezone(date_default_timezone_get())->startOfMinute();
if (Ejaculation::where(['user_id' => $webhook->user_id, 'ejaculated_date' => $ejaculatedDate])->count()) {
return response()->json([
'status' => 422,
'error' => [
'message' => 'Checkin already exists in this time',
]
], 422);
}
$ejaculation = DB::transaction(function () use ($inputs, $webhook, $ejaculatedDate) {
$ejaculation = Ejaculation::create([
'user_id' => $webhook->user_id,
'ejaculated_date' => $ejaculatedDate,
'note' => $inputs['note'] ?? '',
'link' => $inputs['link'] ?? '',
'source' => Ejaculation::SOURCE_WEBHOOK,
'is_private' => (bool)($inputs['is_private'] ?? false),
'is_too_sensitive' => (bool)($inputs['is_too_sensitive'] ?? false),
'checkin_webhook_id' => $webhook->id
]);
$tagIds = [];
if (!empty($inputs['tags'])) {
foreach ($inputs['tags'] as $tag) {
$tag = trim($tag);
if ($tag === '') {
continue;
}
$tag = Tag::firstOrCreate(['name' => $tag]);
$tagIds[] = $tag->id;
}
}
$ejaculation->tags()->sync($tagIds);
return $ejaculation;
});
if (!empty($ejaculation->link)) {
event(new LinkDiscovered($ejaculation->link));
}
return response()->json([
'status' => 200,
'checkin' => new EjaculationResource($ejaculation)
]);
}
}

View File

@ -16,26 +16,17 @@ class EjaculationController extends Controller
{
public function create(Request $request)
{
$tags = old('tags') ?? $request->input('tags', '');
if (!empty($tags)) {
$tags = explode(' ', $tags);
}
$errors = $request->session()->get('errors');
$initialState = [
'fields' => [
'date' => old('date') ?? $request->input('date', date('Y/m/d')),
'time' => old('time') ?? $request->input('time', date('H:i')),
'link' => old('link') ?? $request->input('link', ''),
'tags' => $tags,
'note' => old('note') ?? $request->input('note', ''),
'is_private' => old('is_private') ?? $request->input('is_private', 0) == 1,
'is_too_sensitive' => old('is_too_sensitive') ?? $request->input('is_too_sensitive', 0) == 1
],
'errors' => isset($errors) ? $errors->getMessages() : null
$defaults = [
'date' => $request->input('date', date('Y/m/d')),
'time' => $request->input('time', date('H:i')),
'link' => $request->input('link', ''),
'tags' => $request->input('tags', ''),
'note' => $request->input('note', ''),
'is_private' => $request->input('is_private', 0) == 1,
'is_too_sensitive' => $request->input('is_too_sensitive', 0) == 1
];
return view('ejaculation.checkin')->with('initialState', $initialState);
return view('ejaculation.checkin')->with('defaults', $defaults);
}
public function store(Request $request)
@ -121,36 +112,13 @@ class EjaculationController extends Controller
return view('ejaculation.show')->with(compact('user', 'ejaculation', 'ejaculatedSpan'));
}
public function edit(Request $request, $id)
public function edit($id)
{
$ejaculation = Ejaculation::findOrFail($id);
$this->authorize('edit', $ejaculation);
if (old('tags') === null) {
$tags = $ejaculation->tags->pluck('name');
} else {
$tags = old('tags');
if (!empty($tags)) {
$tags = explode(' ', $tags);
}
}
$errors = $request->session()->get('errors');
$initialState = [
'fields' => [
'date' => old('date') ?? $ejaculation->ejaculated_date->format('Y/m/d'),
'time' => old('time') ?? $ejaculation->ejaculated_date->format('H:i'),
'link' => old('link') ?? $ejaculation->link,
'tags' => $tags,
'note' => old('note') ?? $ejaculation->note,
'is_private' => is_bool(old('is_private')) ? old('is_private') : $ejaculation->note,
'is_too_sensitive' => is_bool(old('is_too_sensitive')) ? old('is_too_sensitive') : $ejaculation->is_too_sensitive
],
'errors' => isset($errors) ? $errors->getMessages() : null
];
return view('ejaculation.edit')->with(compact('ejaculation', 'initialState'));
return view('ejaculation.edit')->with(compact('ejaculation'));
}
public function update(Request $request, $id)

View File

@ -71,7 +71,7 @@ SQL
->select('ejaculations.*')
->with('user', 'tags')
->withLikes()
->visibleToTimeline()
->onlyWebCheckin()
->take(21)
->get();

View File

@ -2,7 +2,6 @@
namespace App\Http\Controllers;
use App\CheckinWebhook;
use App\DeactivatedUser;
use App\Ejaculation;
use App\Exceptions\CsvImportException;
@ -76,46 +75,6 @@ class SettingController extends Controller
return redirect()->route('setting.privacy')->with('status', 'プライバシー設定を更新しました。');
}
public function webhooks()
{
$webhooks = Auth::user()->checkinWebhooks;
$webhooksLimit = CheckinWebhook::PER_USER_LIMIT;
return view('setting.webhooks')->with(compact('webhooks', 'webhooksLimit'));
}
public function storeWebhooks(Request $request)
{
$validated = $request->validate([
'name' => [
'required',
'string',
'max:255',
Rule::unique('checkin_webhooks', 'name')->where(function ($query) {
return $query->where('user_id', Auth::id());
})
]
], [], [
'name' => '名前'
]);
if (Auth::user()->checkinWebhooks()->count() >= CheckinWebhook::PER_USER_LIMIT) {
return redirect()->route('setting.webhooks')
->with('status', CheckinWebhook::PER_USER_LIMIT . '件以上のWebhookを作成することはできません。');
}
Auth::user()->checkinWebhooks()->create($validated);
return redirect()->route('setting.webhooks')->with('status', '作成しました。');
}
public function destroyWebhooks(CheckinWebhook $webhook)
{
$webhook->delete();
return redirect()->route('setting.webhooks')->with('status', '削除しました。');
}
public function import()
{
return view('setting.import');

View File

@ -19,7 +19,7 @@ class TimelineController extends Controller
->select('ejaculations.*')
->with('user', 'tags')
->withLikes()
->visibleToTimeline()
->onlyWebCheckin()
->paginate(21);
return view('timeline.public')->with(compact('ejaculations'));

View File

@ -38,17 +38,15 @@ class Kernel extends HttpKernel
\App\Http\Middleware\NormalizeLineEnding::class,
],
// 現時点では内部APIしかないので、認証の手間を省くためにステートフルにしている。
'api' => [
\App\Http\Middleware\EnforceJson::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
'stateful' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
]
'throttle:60,1',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
];
/**

View File

@ -1,25 +0,0 @@
<?php
namespace App\Http\Middleware;
use Closure;
/**
* Request headerに Accept: application/json を上書きする。APIエンドポイント用。
*/
class EnforceJson
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$request->headers->set('Accept', 'application/json');
return $next($request);
}
}

View File

@ -1,28 +0,0 @@
<?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
class EjaculationResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
return [
'id' => $this->id,
'checked_in_at' => $this->ejaculated_date->format(\DateTime::ATOM),
'note' => $this->note,
'link' => $this->link,
'tags' => $this->tags->pluck('name'),
'source' => $this->source,
'is_private' => $this->is_private,
'is_too_sensitive' => $this->is_too_sensitive,
];
}
}

View File

@ -2,8 +2,6 @@
namespace App;
use Carbon\CarbonInterface;
use GuzzleHttp\Exception\RequestException;
use Illuminate\Database\Eloquent\Model;
class Metadata extends Model
@ -15,66 +13,10 @@ class Metadata extends Model
protected $fillable = ['url', 'title', 'description', 'image', 'expires_at'];
protected $visible = ['url', 'title', 'description', 'image', 'expires_at', 'tags'];
protected $dates = ['created_at', 'updated_at', 'expires_at', 'error_at'];
protected $dates = ['created_at', 'updated_at', 'expires_at'];
public function tags()
{
return $this->belongsToMany(Tag::class)->withTimestamps();
}
public function needRefresh(): bool
{
return $this->isExpired() || $this->error_at !== null;
}
public function isExpired(): bool
{
return $this->expires_at !== null && $this->expires_at < now();
}
public function storeException(CarbonInterface $error_at, \Exception $exception): self
{
$this->prepareFieldsOnError();
$this->error_at = $error_at;
$this->error_exception_class = get_class($exception);
$this->error_body = $exception->getMessage();
if ($exception instanceof RequestException) {
$this->error_http_code = $exception->getCode();
} else {
$this->error_http_code = null;
}
$this->error_count++;
return $this;
}
public function storeError(CarbonInterface $error_at, string $body, ?int $httpCode = null): self
{
$this->prepareFieldsOnError();
$this->error_at = $error_at;
$this->error_exception_class = null;
$this->error_body = $body;
$this->error_http_code = $httpCode;
$this->error_count++;
return $this;
}
public function clearError(): self
{
$this->error_at = null;
$this->error_exception_class = null;
$this->error_body = null;
$this->error_http_code = null;
$this->error_count = 0;
return $this;
}
private function prepareFieldsOnError()
{
$this->title = $this->title ?? '';
$this->description = $this->description ?? '';
$this->image = $this->image ?? '';
}
}

View File

@ -1,30 +0,0 @@
<?php
namespace App\MetadataResolver;
use RuntimeException;
use Throwable;
/**
* ContentProviderの提供するrobots.txtによってクロールが拒否された場合にスローされます。
*/
class DisallowedByProviderException extends RuntimeException
{
private $url;
public function __construct(string $url, Throwable $previous = null)
{
parent::__construct("Access denied by robots.txt: $url", 0, $previous);
$this->url = $url;
}
public function getUrl(): string
{
return $this->url;
}
public function getHost(): string
{
return parse_url($this->url, PHP_URL_HOST);
}
}

View File

@ -1,16 +0,0 @@
<?php
namespace App\MetadataResolver;
use Throwable;
/**
* 規定回数以上の解決失敗により、メタデータの取得が不能となっている場合にスローされます。
*/
class ResolverCircuitBreakException extends \RuntimeException
{
public function __construct(int $errorCount, string $url, Throwable $previous = null)
{
parent::__construct("{$errorCount}回失敗しているためメタデータの取得を中断しました: {$url}", 0, $previous);
}
}

View File

@ -1,10 +0,0 @@
<?php
namespace App\MetadataResolver;
/**
* MetadataResolver内で未キャッチの例外が発生した場合にスローされます。
*/
class UncaughtResolverException extends \RuntimeException
{
}

View File

@ -1,62 +0,0 @@
<?php
namespace App\Rules;
use Illuminate\Contracts\Validation\Rule;
class FuzzyBoolean implements Rule
{
public static function isTruthy($value): bool
{
if ($value === 1 || $value === '1') {
return true;
}
$lower = strtolower((string)$value);
return $lower === 'true';
}
public static function isFalsy($value): bool
{
if ($value === null || $value === '' || $value === 0 || $value === '0') {
return true;
}
$lower = strtolower((string)$value);
return $lower === 'false';
}
/**
* Create a new rule instance.
*
* @return void
*/
public function __construct()
{
//
}
/**
* Determine if the validation rule passes.
*
* @param string $attribute
* @param mixed $value
* @return bool
*/
public function passes($attribute, $value)
{
return self::isTruthy($value) || self::isFalsy($value);
}
/**
* Get the validation error message.
*
* @return string
*/
public function message()
{
return __('validation.boolean');
}
}

View File

@ -30,7 +30,7 @@ class CheckinCsvExporter
$csv->addStreamFilter('convert.mbstring.encoding.UTF-8:SJIS-win');
}
$header = ['日時', 'ノート', 'オカズリンク', '非公開', 'センシティブ'];
$header = ['日時', 'ノート', 'オカズリンク'];
for ($i = 1; $i <= 32; $i++) {
$header[] = "タグ{$i}";
}
@ -45,8 +45,6 @@ class CheckinCsvExporter
$ejaculation->ejaculated_date->format('Y/m/d H:i'),
$ejaculation->note,
$ejaculation->link,
self::formatBoolean($ejaculation->is_private),
self::formatBoolean($ejaculation->is_too_sensitive),
];
foreach ($ejaculation->tags->take(32) as $tag) {
$record[] = $tag->name;
@ -56,9 +54,4 @@ class CheckinCsvExporter
});
});
}
private static function formatBoolean($value): string
{
return $value ? 'true' : 'false';
}
}

View File

@ -6,7 +6,6 @@ namespace App\Services;
use App\Ejaculation;
use App\Exceptions\CsvImportException;
use App\Rules\CsvDateTime;
use App\Rules\FuzzyBoolean;
use App\Tag;
use App\User;
use Carbon\Carbon;
@ -76,8 +75,6 @@ class CheckinCsvImporter
'日時' => ['required', new CsvDateTime()],
'ノート' => 'nullable|string|max:500',
'オカズリンク' => 'nullable|url|max:2000',
'非公開' => ['nullable', new FuzzyBoolean()],
'センシティブ' => ['nullable', new FuzzyBoolean()],
]);
if ($validator->fails()) {
@ -91,12 +88,6 @@ class CheckinCsvImporter
$ejaculation->note = str_replace(["\r\n", "\r"], "\n", $record['ノート'] ?? '');
$ejaculation->link = $record['オカズリンク'] ?? '';
$ejaculation->source = Ejaculation::SOURCE_CSV;
if (isset($record['非公開'])) {
$ejaculation->is_private = FuzzyBoolean::isTruthy($record['非公開']);
}
if (isset($record['センシティブ'])) {
$ejaculation->is_too_sensitive = FuzzyBoolean::isTruthy($record['センシティブ']);
}
try {
$tags = $this->parseTags($line, $record);

View File

@ -2,26 +2,17 @@
namespace App\Services;
use App\ContentProvider;
use App\Metadata;
use App\MetadataResolver\DeniedHostException;
use App\MetadataResolver\DisallowedByProviderException;
use App\MetadataResolver\MetadataResolver;
use App\MetadataResolver\ResolverCircuitBreakException;
use App\MetadataResolver\UncaughtResolverException;
use App\Tag;
use App\Utilities\Formatter;
use Carbon\Carbon;
use Carbon\CarbonInterface;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\TransferException;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
class MetadataResolveService
{
/** @var int メタデータの解決を中断するエラー回数。この回数以上エラーしていたら処理は行わない。 */
const CIRCUIT_BREAK_COUNT = 5;
/** @var MetadataResolver */
private $resolver;
/** @var Formatter */
@ -33,13 +24,6 @@ class MetadataResolveService
$this->formatter = $formatter;
}
/**
* メタデータをキャッシュまたはリモートに問い合わせて取得します。
* @param string $url メタデータを取得したいURL
* @return Metadata 取得できたメタデータ
* @throws DeniedHostException アクセス先がブラックリスト入りしているため取得できなかった場合にスロー
* @throws UncaughtResolverException Resolver内で例外が発生して取得できなかった場合にスロー
*/
public function execute(string $url): Metadata
{
// URLの正規化
@ -50,252 +34,34 @@ class MetadataResolveService
throw new DeniedHostException($url);
}
$metadata = Metadata::find($url);
return DB::transaction(function () use ($url) {
// 無かったら取得
// TODO: ある程度古かったら再取得とかありだと思う
$metadata = Metadata::find($url);
if ($metadata == null || ($metadata->expires_at !== null && $metadata->expires_at < now())) {
try {
$resolved = $this->resolver->resolve($url);
$metadata = Metadata::updateOrCreate(['url' => $url], [
'title' => $resolved->title,
'description' => $resolved->description,
'image' => $resolved->image,
'expires_at' => $resolved->expires_at
]);
// 無かったら取得
// TODO: ある程度古かったら再取得とかありだと思う
if ($metadata == null || $metadata->needRefresh()) {
$hostWithPort = $this->getHostWithPortFromUrl($url);
$metadata = $this->hostLock($hostWithPort, function (?CarbonInterface $lastAccess) use ($url) {
// HostLockの解放待ちをしている間に、他のプロセスで取得完了しているかもしれない
$metadata = Metadata::find($url);
if ($metadata !== null && !$metadata->needRefresh()) {
return $metadata;
}
$this->checkProviderPolicy($url, $lastAccess);
return $this->resolve($url, $metadata);
});
}
return $metadata;
}
/**
* URLからホスト部とポート部を抽出
* @param string $url
* @return string
*/
private function getHostWithPortFromUrl(string $url): string
{
$parts = parse_url($url);
$host = $parts['host'];
if (isset($parts['port'])) {
$host .= ':' . $parts['port'];
}
return $host;
}
/**
* アクセス先ホスト単位の排他ロックを取って処理を実行
* @param string $host
* @param callable $fn
* @return mixed return of $fn
* @throws \RuntimeException いろいろな死に方をする
*/
private function hostLock(string $host, callable $fn)
{
$lockDir = storage_path('content_providers_lock');
if (!file_exists($lockDir)) {
if (!mkdir($lockDir)) {
throw new \RuntimeException("Lock failed! Can't create lock directory.");
}
}
$lockFile = $lockDir . DIRECTORY_SEPARATOR . $host;
$fp = fopen($lockFile, 'c+b');
if ($fp === false) {
throw new \RuntimeException("Lock failed! Can't open lock file.");
}
try {
if (!flock($fp, LOCK_EX)) {
throw new \RuntimeException("Lock failed! Can't lock file.");
}
try {
$accessInfoText = stream_get_contents($fp);
if ($accessInfoText !== false) {
$accessInfo = json_decode($accessInfoText, true);
}
$result = $fn(isset($accessInfo['time']) ? new Carbon($accessInfo['time']) : null);
$accessInfo = [
'time' => now()->toIso8601String()
];
fseek($fp, 0);
if (fwrite($fp, json_encode($accessInfo)) === false) {
throw new \RuntimeException("I/O Error! Can't write to lock file.");
}
return $result;
} finally {
if (!flock($fp, LOCK_UN)) {
throw new \RuntimeException("Unlock failed! Can't unlock file.");
}
}
} finally {
if (!fclose($fp)) {
throw new \RuntimeException("Unlock failed! Can't close lock file.");
}
}
}
/**
* 指定したメタデータURLのホストが持つrobots.txtをダウンロードします。
* @param string $url メタデータのURL
* @return string
*/
private function fetchRobotsTxt(string $url): ?string
{
$parts = parse_url($url);
$robotsUrl = http_build_url([
'scheme' => $parts['scheme'],
'host' => $parts['host'],
'port' => $parts['port'] ?? null,
'path' => '/robots.txt'
]);
$client = app(Client::class);
try {
$res = $client->get($robotsUrl);
return (string) $res->getBody();
} catch (\Exception $e) {
Log::error("robots.txtの取得に失敗: {$e}");
return null;
}
}
/**
* ContentProviderポリシー情報との照合を行い、アクセス可能かチェックします。アクセスできない場合は例外をスローします。
* @param string $url メタデータを取得したいURL
* @param CarbonInterface|null $lastAccess アクセス先ホストへの最終アクセス日時 (記録がある場合)
* @throws DeniedHostException アクセス先がTissue内のブラックリストに入っている場合にスロー
* @throws DisallowedByProviderException アクセス先のrobots.txtによって拒否されている場合にスロー
*/
private function checkProviderPolicy(string $url, ?CarbonInterface $lastAccess): void
{
DB::beginTransaction();
try {
$hostWithPort = $this->getHostWithPortFromUrl($url);
$contentProvider = ContentProvider::sharedLock()->find($hostWithPort);
if ($contentProvider === null) {
$contentProvider = ContentProvider::create([
'host' => $hostWithPort,
'robots' => $this->fetchRobotsTxt($url),
'robots_cached_at' => now(),
]);
}
if ($contentProvider->is_blocked) {
throw new DeniedHostException($url);
}
// 連続アクセス制限
if ($lastAccess !== null) {
$elapsedSeconds = $lastAccess->diffInSeconds(now(), false);
if ($elapsedSeconds < $contentProvider->access_interval_sec) {
if ($elapsedSeconds < 0) {
$wait = abs($elapsedSeconds) + $contentProvider->access_interval_sec;
} else {
$wait = $contentProvider->access_interval_sec - $elapsedSeconds;
$tagIds = [];
foreach ($resolved->normalizedTags() as $tagName) {
$tag = Tag::firstOrCreate(['name' => $tagName]);
$tagIds[] = $tag->id;
}
sleep($wait);
$metadata->tags()->sync($tagIds);
} catch (TransferException $e) {
// 何らかの通信エラーによってメタデータの取得に失敗した時、とりあえずエラーログにURLを残す
Log::error(self::class . ': メタデータの取得に失敗 URL=' . $url);
throw $e;
}
}
// Fetch robots.txt
if ($contentProvider->robots_cached_at->diffInDays(now()) >= 7) {
$contentProvider->update([
'robots' => $this->fetchRobotsTxt($url),
'robots_cached_at' => now(),
]);
}
// Check robots.txt
$robotsParser = new \RobotsTxtParser($contentProvider->robots);
$robotsParser->setUserAgent('TissueBot');
$robotsDelay = $robotsParser->getDelay();
if ($robotsDelay !== 0 && $robotsDelay >= $contentProvider->access_interval_sec) {
$contentProvider->access_interval_sec = (int) $robotsDelay;
$contentProvider->save();
}
if ($robotsParser->isDisallowed(parse_url($url, PHP_URL_PATH))) {
throw new DisallowedByProviderException($url);
}
DB::commit();
} catch (DeniedHostException | DisallowedByProviderException $e) {
// ContentProviderのデータ更新は行うため
DB::commit();
throw $e;
} catch (\Exception $e) {
DB::rollBack();
throw $e;
}
}
/**
* メタデータをリモートサーバに問い合わせて取得します。
* @param string $url メタデータを取得したいURL
* @param Metadata|null $metadata キャッシュ済のメタデータ (存在する場合)
* @return Metadata 取得できたメタデータ
* @throws UncaughtResolverException Resolver内で例外が発生して取得できなかった場合にスロー
* @throws ResolverCircuitBreakException 規定回数以上の解決失敗により、メタデータの取得が不能となっている場合にスロー
*/
private function resolve(string $url, ?Metadata $metadata): Metadata
{
DB::beginTransaction();
try {
if ($metadata === null) {
$metadata = new Metadata(['url' => $url]);
}
if ($metadata->error_count >= self::CIRCUIT_BREAK_COUNT) {
throw new ResolverCircuitBreakException($metadata->error_count, $url);
}
try {
$resolved = $this->resolver->resolve($url);
} catch (\Exception $e) {
$metadata->storeException(now(), $e);
$metadata->save();
throw new UncaughtResolverException(implode(': ', [
$metadata->error_count . '回目のメタデータ取得失敗', get_class($e), $e->getMessage()
]), 0, $e);
}
$metadata->fill([
'title' => $resolved->title,
'description' => $resolved->description,
'image' => $resolved->image,
'expires_at' => $resolved->expires_at
]);
$metadata->clearError();
$metadata->save();
$tagIds = [];
foreach ($resolved->normalizedTags() as $tagName) {
$tag = Tag::firstOrCreate(['name' => $tagName]);
$tagIds[] = $tag->id;
}
$metadata->tags()->sync($tagIds);
DB::commit();
return $metadata;
} catch (UncaughtResolverException $e) {
// Metadataにエラー情報を記録するため
DB::commit();
throw $e;
} catch (\Exception $e) {
DB::rollBack();
throw $e;
}
});
}
}

View File

@ -71,9 +71,4 @@ class User extends Authenticatable
{
return $this->hasMany(Like::class);
}
public function checkinWebhooks()
{
return $this->hasMany(CheckinWebhook::class);
}
}

View File

@ -33,8 +33,7 @@
"sentry/sentry-laravel": "1.8.0",
"staudenmeir/eloquent-eager-limit": "^1.0",
"symfony/css-selector": "^4.3",
"symfony/dom-crawler": "^4.3",
"t1gor/robots-txt-parser": "^0.2.4"
"symfony/dom-crawler": "^4.3"
},
"require-dev": {
"barryvdh/laravel-debugbar": "^3.1",

394
composer.lock generated
View File

@ -4,7 +4,7 @@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically"
],
"content-hash": "bbb184ff943ae3a938a8370d94b6afb2",
"content-hash": "1bba68b609be6a0dcdaf05d72e8eb759",
"packages": [
{
"name": "anhskohbo/no-captcha",
@ -394,20 +394,6 @@
"sqlserver",
"sqlsrv"
],
"funding": [
{
"url": "https://www.doctrine-project.org/sponsorship.html",
"type": "custom"
},
{
"url": "https://www.patreon.com/phpdoctrine",
"type": "patreon"
},
{
"url": "https://tidelift.com/funding/github/packagist/doctrine%2Fdbal",
"type": "tidelift"
}
],
"time": "2020-04-20T17:19:26+00:00"
},
{
@ -1617,12 +1603,6 @@
"transform",
"write"
],
"funding": [
{
"url": "https://github.com/sponsors/nyamsprod",
"type": "github"
}
],
"time": "2020-03-17T15:15:35+00:00"
},
{
@ -1707,12 +1687,6 @@
"sftp",
"storage"
],
"funding": [
{
"url": "https://offset.earth/frankdejonge",
"type": "other"
}
],
"time": "2020-05-18T15:13:39+00:00"
},
{
@ -1762,16 +1736,16 @@
},
{
"name": "monolog/monolog",
"version": "2.1.1",
"version": "2.1.0",
"source": {
"type": "git",
"url": "https://github.com/Seldaek/monolog.git",
"reference": "f9eee5cec93dfb313a38b6b288741e84e53f02d5"
"reference": "38914429aac460e8e4616c8cb486ecb40ec90bb1"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/Seldaek/monolog/zipball/f9eee5cec93dfb313a38b6b288741e84e53f02d5",
"reference": "f9eee5cec93dfb313a38b6b288741e84e53f02d5",
"url": "https://api.github.com/repos/Seldaek/monolog/zipball/38914429aac460e8e4616c8cb486ecb40ec90bb1",
"reference": "38914429aac460e8e4616c8cb486ecb40ec90bb1",
"shasum": ""
},
"require": {
@ -1839,17 +1813,7 @@
"logging",
"psr-3"
],
"funding": [
{
"url": "https://github.com/Seldaek",
"type": "github"
},
{
"url": "https://tidelift.com/funding/github/packagist/monolog/monolog",
"type": "tidelift"
}
],
"time": "2020-07-23T08:41:23+00:00"
"time": "2020-05-22T08:12:19+00:00"
},
{
"name": "nesbot/carbon",
@ -3444,16 +3408,16 @@
},
{
"name": "symfony/console",
"version": "v4.4.11",
"version": "v4.4.10",
"source": {
"type": "git",
"url": "https://github.com/symfony/console.git",
"reference": "55d07021da933dd0d633ffdab6f45d5b230c7e02"
"reference": "326b064d804043005526f5a0494cfb49edb59bb0"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/symfony/console/zipball/55d07021da933dd0d633ffdab6f45d5b230c7e02",
"reference": "55d07021da933dd0d633ffdab6f45d5b230c7e02",
"url": "https://api.github.com/repos/symfony/console/zipball/326b064d804043005526f5a0494cfb49edb59bb0",
"reference": "326b064d804043005526f5a0494cfb49edb59bb0",
"shasum": ""
},
"require": {
@ -3531,24 +3495,24 @@
"type": "tidelift"
}
],
"time": "2020-07-06T13:18:39+00:00"
"time": "2020-05-30T20:06:45+00:00"
},
{
"name": "symfony/css-selector",
"version": "v4.4.11",
"version": "v4.4.10",
"source": {
"type": "git",
"url": "https://github.com/symfony/css-selector.git",
"reference": "bf17dc9f6ce144e41f786c32435feea4d8e11dcc"
"reference": "afc26133a6fbdd4f8842e38893e0ee4685c7c94b"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/symfony/css-selector/zipball/bf17dc9f6ce144e41f786c32435feea4d8e11dcc",
"reference": "bf17dc9f6ce144e41f786c32435feea4d8e11dcc",
"url": "https://api.github.com/repos/symfony/css-selector/zipball/afc26133a6fbdd4f8842e38893e0ee4685c7c94b",
"reference": "afc26133a6fbdd4f8842e38893e0ee4685c7c94b",
"shasum": ""
},
"require": {
"php": ">=7.1.3"
"php": "^7.1.3"
},
"type": "library",
"extra": {
@ -3598,7 +3562,7 @@
"type": "tidelift"
}
],
"time": "2020-07-05T09:39:30+00:00"
"time": "2020-03-27T16:54:36+00:00"
},
{
"name": "symfony/debug",
@ -3733,16 +3697,16 @@
},
{
"name": "symfony/dom-crawler",
"version": "v4.4.11",
"version": "v4.4.10",
"source": {
"type": "git",
"url": "https://github.com/symfony/dom-crawler.git",
"reference": "72b3a65ddd5052cf6d65eac6669748ed311f39bf"
"reference": "c18354d5a0bb84c945f6257c51b971d52f10c614"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/symfony/dom-crawler/zipball/72b3a65ddd5052cf6d65eac6669748ed311f39bf",
"reference": "72b3a65ddd5052cf6d65eac6669748ed311f39bf",
"url": "https://api.github.com/repos/symfony/dom-crawler/zipball/c18354d5a0bb84c945f6257c51b971d52f10c614",
"reference": "c18354d5a0bb84c945f6257c51b971d52f10c614",
"shasum": ""
},
"require": {
@ -3804,7 +3768,7 @@
"type": "tidelift"
}
],
"time": "2020-07-23T08:31:43+00:00"
"time": "2020-05-23T00:03:06+00:00"
},
{
"name": "symfony/error-handler",
@ -4102,16 +4066,16 @@
},
{
"name": "symfony/http-foundation",
"version": "v4.4.11",
"version": "v4.4.10",
"source": {
"type": "git",
"url": "https://github.com/symfony/http-foundation.git",
"reference": "3675676b6a47f3e71d3ab10bcf53fb9239eb77e6"
"reference": "3adfbd7098c850b02d107330b7b9deacf2581578"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/symfony/http-foundation/zipball/3675676b6a47f3e71d3ab10bcf53fb9239eb77e6",
"reference": "3675676b6a47f3e71d3ab10bcf53fb9239eb77e6",
"url": "https://api.github.com/repos/symfony/http-foundation/zipball/3adfbd7098c850b02d107330b7b9deacf2581578",
"reference": "3adfbd7098c850b02d107330b7b9deacf2581578",
"shasum": ""
},
"require": {
@ -4167,7 +4131,7 @@
"type": "tidelift"
}
],
"time": "2020-07-23T09:48:09+00:00"
"time": "2020-05-23T09:11:46+00:00"
},
{
"name": "symfony/http-kernel",
@ -4276,16 +4240,16 @@
},
{
"name": "symfony/mime",
"version": "v5.1.3",
"version": "v5.1.2",
"source": {
"type": "git",
"url": "https://github.com/symfony/mime.git",
"reference": "149fb0ad35aae3c7637b496b38478797fa6a7ea6"
"reference": "c0c418f05e727606e85b482a8591519c4712cf45"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/symfony/mime/zipball/149fb0ad35aae3c7637b496b38478797fa6a7ea6",
"reference": "149fb0ad35aae3c7637b496b38478797fa6a7ea6",
"url": "https://api.github.com/repos/symfony/mime/zipball/c0c418f05e727606e85b482a8591519c4712cf45",
"reference": "c0c418f05e727606e85b482a8591519c4712cf45",
"shasum": ""
},
"require": {
@ -4349,7 +4313,7 @@
"type": "tidelift"
}
],
"time": "2020-07-23T10:04:31+00:00"
"time": "2020-06-09T15:07:35+00:00"
},
{
"name": "symfony/options-resolver",
@ -4423,7 +4387,7 @@
},
{
"name": "symfony/polyfill-ctype",
"version": "v1.18.1",
"version": "v1.18.0",
"source": {
"type": "git",
"url": "https://github.com/symfony/polyfill-ctype.git",
@ -4742,7 +4706,7 @@
},
{
"name": "symfony/polyfill-mbstring",
"version": "v1.18.1",
"version": "v1.18.0",
"source": {
"type": "git",
"url": "https://github.com/symfony/polyfill-mbstring.git",
@ -4819,16 +4783,16 @@
},
{
"name": "symfony/polyfill-php70",
"version": "v1.18.0",
"version": "v1.17.1",
"source": {
"type": "git",
"url": "https://github.com/symfony/polyfill-php70.git",
"reference": "0dd93f2c578bdc9c72697eaa5f1dd25644e618d3"
"reference": "471b096aede7025bace8eb356b9ac801aaba7e2d"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/symfony/polyfill-php70/zipball/0dd93f2c578bdc9c72697eaa5f1dd25644e618d3",
"reference": "0dd93f2c578bdc9c72697eaa5f1dd25644e618d3",
"url": "https://api.github.com/repos/symfony/polyfill-php70/zipball/471b096aede7025bace8eb356b9ac801aaba7e2d",
"reference": "471b096aede7025bace8eb356b9ac801aaba7e2d",
"shasum": ""
},
"require": {
@ -4838,7 +4802,7 @@
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "1.18-dev"
"dev-master": "1.17-dev"
},
"thanks": {
"name": "symfony/polyfill",
@ -4892,7 +4856,7 @@
"type": "tidelift"
}
],
"time": "2020-07-14T12:35:20+00:00"
"time": "2020-06-06T08:46:27+00:00"
},
{
"name": "symfony/polyfill-php72",
@ -5596,16 +5560,16 @@
},
{
"name": "symfony/var-dumper",
"version": "v4.4.11",
"version": "v4.4.10",
"source": {
"type": "git",
"url": "https://github.com/symfony/var-dumper.git",
"reference": "2125805a1a4e57f2340bc566c3013ca94d2722dc"
"reference": "56b3aa5eab0ac6720dcd559fd1d590ce301594ac"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/symfony/var-dumper/zipball/2125805a1a4e57f2340bc566c3013ca94d2722dc",
"reference": "2125805a1a4e57f2340bc566c3013ca94d2722dc",
"url": "https://api.github.com/repos/symfony/var-dumper/zipball/56b3aa5eab0ac6720dcd559fd1d590ce301594ac",
"reference": "56b3aa5eab0ac6720dcd559fd1d590ce301594ac",
"shasum": ""
},
"require": {
@ -5683,64 +5647,7 @@
"type": "tidelift"
}
],
"time": "2020-06-24T13:34:53+00:00"
},
{
"name": "t1gor/robots-txt-parser",
"version": "v0.2.4",
"source": {
"type": "git",
"url": "https://github.com/t1gor/Robots.txt-Parser-Class.git",
"reference": "7ff08da5625fb4f72d17b1528c60aadb184e9e68"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/t1gor/Robots.txt-Parser-Class/zipball/7ff08da5625fb4f72d17b1528c60aadb184e9e68",
"reference": "7ff08da5625fb4f72d17b1528c60aadb184e9e68",
"shasum": ""
},
"require": {
"ext-mbstring": "*",
"php": ">=5.5.0",
"vipnytt/useragentparser": "^1.0"
},
"require-dev": {
"codeclimate/php-test-reporter": ">=0.2",
"phpunit/phpunit": "~3.7"
},
"type": "library",
"autoload": {
"classmap": [
"source/robotstxtparser.php"
]
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Igor Timoshenkov",
"email": "igor.timoshenkov@gmail.com",
"role": "creator"
},
{
"name": "Jan-Petter Gundersen",
"email": "jpg@vipnytt.no",
"role": "contributor"
}
],
"description": "PHP class to parse robots.txt rules according to Google, Yandex, W3C and The Web Robots Pages specifications.",
"homepage": "https://github.com/t1gor/Robots.txt-Parser-Class",
"keywords": [
"The Web Robots Pages",
"W3C",
"google",
"parser",
"robots.txt",
"yandex"
],
"time": "2018-07-21T20:01:19+00:00"
"time": "2020-05-30T20:06:45+00:00"
},
{
"name": "tijsverkoyen/css-to-inline-styles",
@ -5791,64 +5698,6 @@
"homepage": "https://github.com/tijsverkoyen/CssToInlineStyles",
"time": "2020-07-13T06:12:54+00:00"
},
{
"name": "vipnytt/useragentparser",
"version": "v1.0.4",
"source": {
"type": "git",
"url": "https://github.com/VIPnytt/UserAgentParser.git",
"reference": "c5a6718a57088e0d45c2e36f09efabc4e008bd8c"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/VIPnytt/UserAgentParser/zipball/c5a6718a57088e0d45c2e36f09efabc4e008bd8c",
"reference": "c5a6718a57088e0d45c2e36f09efabc4e008bd8c",
"shasum": ""
},
"require": {
"php": "^5.5 || ^7.0"
},
"require-dev": {
"phpunit/phpunit": "^4.8.35 || ^5.7 || ^6.5"
},
"type": "library",
"autoload": {
"psr-4": {
"vipnytt\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "VIP nytt AS",
"email": "support@vipnytt.no",
"role": "Owner"
},
{
"name": "Jan-Petter Gundersen",
"email": "jpg@vipnytt.no",
"role": "Developer"
}
],
"description": "User-Agent parser for robot rule sets",
"homepage": "https://github.com/VIPnytt/UserAgentParser",
"keywords": [
"REP",
"Robots Exclusion Protocol",
"Robots meta tag",
"crawler",
"robot",
"robots.txt",
"spider",
"user-agent",
"useragent",
"x-robots-tag"
],
"time": "2017-12-17T14:23:27+00:00"
},
{
"name": "vlucas/phpdotenv",
"version": "v3.6.7",
@ -5990,12 +5839,6 @@
"profiler",
"webprofiler"
],
"funding": [
{
"url": "https://github.com/barryvdh",
"type": "github"
}
],
"time": "2020-05-05T10:53:32+00:00"
},
{
@ -6067,12 +5910,6 @@
"phpstorm",
"sublime"
],
"funding": [
{
"url": "https://github.com/barryvdh",
"type": "github"
}
],
"time": "2020-04-22T09:57:26+00:00"
},
{
@ -6178,16 +6015,6 @@
"ssl",
"tls"
],
"funding": [
{
"url": "https://packagist.com",
"type": "custom"
},
{
"url": "https://tidelift.com/funding/github/packagist/composer/composer",
"type": "tidelift"
}
],
"time": "2020-04-08T08:27:21+00:00"
},
{
@ -6269,16 +6096,6 @@
"dependency",
"package"
],
"funding": [
{
"url": "https://packagist.com",
"type": "custom"
},
{
"url": "https://tidelift.com/funding/github/packagist/composer/composer",
"type": "tidelift"
}
],
"time": "2020-05-06T08:28:10+00:00"
},
{
@ -6601,16 +6418,16 @@
},
{
"name": "facade/flare-client-php",
"version": "1.3.4",
"version": "1.3.2",
"source": {
"type": "git",
"url": "https://github.com/facade/flare-client-php.git",
"reference": "0eeb0de4fc1078433f0915010bd8f41e998adcb4"
"reference": "db1e03426e7f9472c9ecd1092aff00f56aa6c004"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/facade/flare-client-php/zipball/0eeb0de4fc1078433f0915010bd8f41e998adcb4",
"reference": "0eeb0de4fc1078433f0915010bd8f41e998adcb4",
"url": "https://api.github.com/repos/facade/flare-client-php/zipball/db1e03426e7f9472c9ecd1092aff00f56aa6c004",
"reference": "db1e03426e7f9472c9ecd1092aff00f56aa6c004",
"shasum": ""
},
"require": {
@ -6618,11 +6435,9 @@
"illuminate/pipeline": "^5.5|^6.0|^7.0",
"php": "^7.1",
"symfony/http-foundation": "^3.3|^4.1|^5.0",
"symfony/mime": "^3.4|^4.0|^5.1",
"symfony/var-dumper": "^3.4|^4.0|^5.0"
},
"require-dev": {
"friendsofphp/php-cs-fixer": "^2.14",
"larapack/dd": "^1.1",
"phpunit/phpunit": "^7.5.16",
"spatie/phpunit-snapshot-assertions": "^2.0"
@ -6653,26 +6468,20 @@
"flare",
"reporting"
],
"funding": [
{
"url": "https://github.com/spatie",
"type": "github"
}
],
"time": "2020-07-13T23:25:57+00:00"
"time": "2020-03-02T15:52:04+00:00"
},
{
"name": "facade/ignition",
"version": "1.16.3",
"version": "1.16.1",
"source": {
"type": "git",
"url": "https://github.com/facade/ignition.git",
"reference": "19674150bb46a4de0ba138c747f538fe7be11dbc"
"reference": "af05ac5ee8587395d7474ec0681c08776a2cb09d"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/facade/ignition/zipball/19674150bb46a4de0ba138c747f538fe7be11dbc",
"reference": "19674150bb46a4de0ba138c747f538fe7be11dbc",
"url": "https://api.github.com/repos/facade/ignition/zipball/af05ac5ee8587395d7474ec0681c08776a2cb09d",
"reference": "af05ac5ee8587395d7474ec0681c08776a2cb09d",
"shasum": ""
},
"require": {
@ -6730,30 +6539,25 @@
"laravel",
"page"
],
"time": "2020-07-13T15:54:05+00:00"
"time": "2020-03-05T12:39:07+00:00"
},
{
"name": "facade/ignition-contracts",
"version": "1.0.1",
"version": "1.0.0",
"source": {
"type": "git",
"url": "https://github.com/facade/ignition-contracts.git",
"reference": "aeab1ce8b68b188a43e81758e750151ad7da796b"
"reference": "f445db0fb86f48e205787b2592840dd9c80ded28"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/facade/ignition-contracts/zipball/aeab1ce8b68b188a43e81758e750151ad7da796b",
"reference": "aeab1ce8b68b188a43e81758e750151ad7da796b",
"url": "https://api.github.com/repos/facade/ignition-contracts/zipball/f445db0fb86f48e205787b2592840dd9c80ded28",
"reference": "f445db0fb86f48e205787b2592840dd9c80ded28",
"shasum": ""
},
"require": {
"php": "^7.1"
},
"require-dev": {
"friendsofphp/php-cs-fixer": "^2.14",
"phpunit/phpunit": "^7.5|^8.0",
"vimeo/psalm": "^3.12"
},
"type": "library",
"autoload": {
"psr-4": {
@ -6779,20 +6583,20 @@
"flare",
"ignition"
],
"time": "2020-07-14T10:10:28+00:00"
"time": "2019-08-30T14:06:08+00:00"
},
{
"name": "filp/whoops",
"version": "2.7.3",
"version": "2.7.2",
"source": {
"type": "git",
"url": "https://github.com/filp/whoops.git",
"reference": "5d5fe9bb3d656b514d455645b3addc5f7ba7714d"
"reference": "17d0d3f266c8f925ebd035cd36f83cf802b47d4a"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/filp/whoops/zipball/5d5fe9bb3d656b514d455645b3addc5f7ba7714d",
"reference": "5d5fe9bb3d656b514d455645b3addc5f7ba7714d",
"url": "https://api.github.com/repos/filp/whoops/zipball/17d0d3f266c8f925ebd035cd36f83cf802b47d4a",
"reference": "17d0d3f266c8f925ebd035cd36f83cf802b47d4a",
"shasum": ""
},
"require": {
@ -6840,7 +6644,7 @@
"throwable",
"whoops"
],
"time": "2020-06-14T09:00:00+00:00"
"time": "2020-05-05T12:28:07+00:00"
},
{
"name": "friendsofphp/php-cs-fixer",
@ -6991,20 +6795,20 @@
},
{
"name": "hamcrest/hamcrest-php",
"version": "v2.0.1",
"version": "v2.0.0",
"source": {
"type": "git",
"url": "https://github.com/hamcrest/hamcrest-php.git",
"reference": "8c3d0a3f6af734494ad8f6fbbee0ba92422859f3"
"reference": "776503d3a8e85d4f9a1148614f95b7a608b046ad"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/hamcrest/hamcrest-php/zipball/8c3d0a3f6af734494ad8f6fbbee0ba92422859f3",
"reference": "8c3d0a3f6af734494ad8f6fbbee0ba92422859f3",
"url": "https://api.github.com/repos/hamcrest/hamcrest-php/zipball/776503d3a8e85d4f9a1148614f95b7a608b046ad",
"reference": "776503d3a8e85d4f9a1148614f95b7a608b046ad",
"shasum": ""
},
"require": {
"php": "^5.3|^7.0|^8.0"
"php": "^5.3|^7.0"
},
"replace": {
"cordoval/hamcrest-php": "*",
@ -7012,13 +6816,14 @@
"kodova/hamcrest-php": "*"
},
"require-dev": {
"phpunit/php-file-iterator": "^1.4 || ^2.0",
"phpunit/phpunit": "^4.8.36 || ^5.7 || ^6.5 || ^7.0"
"phpunit/php-file-iterator": "1.3.3",
"phpunit/phpunit": "~4.0",
"satooshi/php-coveralls": "^1.0"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "2.1-dev"
"dev-master": "2.0-dev"
}
},
"autoload": {
@ -7028,13 +6833,13 @@
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"BSD-3-Clause"
"BSD"
],
"description": "This is the PHP port of Hamcrest Matchers",
"keywords": [
"test"
],
"time": "2020-07-09T08:09:16+00:00"
"time": "2016-01-20T08:20:44+00:00"
},
{
"name": "jakub-onderka/php-console-color",
@ -7255,28 +7060,28 @@
},
{
"name": "mockery/mockery",
"version": "1.4.2",
"version": "1.4.0",
"source": {
"type": "git",
"url": "https://github.com/mockery/mockery.git",
"reference": "20cab678faed06fac225193be281ea0fddb43b93"
"reference": "6c6a7c533469873deacf998237e7649fc6b36223"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/mockery/mockery/zipball/20cab678faed06fac225193be281ea0fddb43b93",
"reference": "20cab678faed06fac225193be281ea0fddb43b93",
"url": "https://api.github.com/repos/mockery/mockery/zipball/6c6a7c533469873deacf998237e7649fc6b36223",
"reference": "6c6a7c533469873deacf998237e7649fc6b36223",
"shasum": ""
},
"require": {
"hamcrest/hamcrest-php": "^2.0.1",
"hamcrest/hamcrest-php": "~2.0",
"lib-pcre": ">=7.0",
"php": "^7.3 || ^8.0"
"php": "^7.3.0"
},
"conflict": {
"phpunit/phpunit": "<8.0"
},
"require-dev": {
"phpunit/phpunit": "^8.5 || ^9.3"
"phpunit/phpunit": "^8.0.0 || ^9.0.0"
},
"type": "library",
"extra": {
@ -7319,7 +7124,7 @@
"test double",
"testing"
],
"time": "2020-08-11T18:10:13+00:00"
"time": "2020-05-19T14:25:16+00:00"
},
{
"name": "myclabs/deep-copy",
@ -8047,7 +7852,6 @@
"keywords": [
"tokenizer"
],
"abandoned": true,
"time": "2019-09-17T06:23:10+00:00"
},
{
@ -8210,12 +8014,6 @@
"highlight.php",
"syntax"
],
"funding": [
{
"url": "https://github.com/allejo",
"type": "github"
}
],
"time": "2020-03-02T05:59:21+00:00"
},
{
@ -8880,16 +8678,6 @@
"parser",
"validator"
],
"funding": [
{
"url": "https://github.com/Seldaek",
"type": "github"
},
{
"url": "https://tidelift.com/funding/github/packagist/seld/jsonlint",
"type": "tidelift"
}
],
"time": "2020-04-30T19:05:18+00:00"
},
{
@ -9066,16 +8854,16 @@
},
{
"name": "symfony/thanks",
"version": "v1.2.9",
"version": "v1.2.8",
"source": {
"type": "git",
"url": "https://github.com/symfony/thanks.git",
"reference": "733cc7b8c09a06c9251bd35d772b453b47d98442"
"reference": "61ef076d0b6b44962d6847c3ba04ee5ba5f785be"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/symfony/thanks/zipball/733cc7b8c09a06c9251bd35d772b453b47d98442",
"reference": "733cc7b8c09a06c9251bd35d772b453b47d98442",
"url": "https://api.github.com/repos/symfony/thanks/zipball/61ef076d0b6b44962d6847c3ba04ee5ba5f785be",
"reference": "61ef076d0b6b44962d6847c3ba04ee5ba5f785be",
"shasum": ""
},
"require": {
@ -9119,7 +8907,7 @@
"type": "tidelift"
}
],
"time": "2020-06-23T10:36:34+00:00"
"time": "2020-06-13T21:20:35+00:00"
},
{
"name": "theseer/tokenizer",
@ -9154,8 +8942,8 @@
"authors": [
{
"name": "Arne Blankerts",
"email": "arne@blankerts.de",
"role": "Developer"
"role": "Developer",
"email": "arne@blankerts.de"
}
],
"description": "A small library for converting tokenized PHP source code into XML and potentially other formats",

View File

@ -1,12 +0,0 @@
<?php
/** @var \Illuminate\Database\Eloquent\Factory $factory */
use App\CheckinWebhook;
use Faker\Generator as Faker;
$factory->define(CheckinWebhook::class, function (Faker $faker) {
return [
'name' => 'example'
];
});

View File

@ -1,14 +0,0 @@
<?php
/** @var \Illuminate\Database\Eloquent\Factory $factory */
use App\ContentProvider;
use Faker\Generator as Faker;
$factory->define(ContentProvider::class, function (Faker $faker) {
return [
'host' => 'example.com',
'robots' => null,
'robots_cached_at' => now(),
];
});

View File

@ -1,39 +0,0 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateCheckinWebhooksTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('checkin_webhooks', function (Blueprint $table) {
$table->string('id', 64);
$table->integer('user_id')->nullable();
$table->string('name');
$table->timestamps();
$table->softDeletes();
$table->primary('id');
$table->index('user_id');
$table->foreign('user_id')->references('id')->on('users')->onDelete('set null');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('checkin_webhooks');
}
}

View File

@ -1,32 +0,0 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class AddCheckinWebhookIdToEjaculations extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('ejaculations', function (Blueprint $table) {
$table->string('checkin_webhook_id', 64)->nullable();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('ejaculations', function (Blueprint $table) {
$table->dropColumn('checkin_webhook_id');
});
}
}

View File

@ -1,36 +0,0 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class AddErrorDataToMetadata extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('metadata', function (Blueprint $table) {
$table->timestamp('error_at')->nullable();
$table->string('error_exception_class')->nullable();
$table->integer('error_http_code')->nullable();
$table->text('error_body')->nullable();
$table->integer('error_count')->default(0);
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('metadata', function (Blueprint $table) {
$table->dropColumn(['error_at', 'error_exception_class', 'error_http_code', 'error_body', 'error_count']);
});
}
}

View File

@ -1,37 +0,0 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateContentProvidersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('content_providers', function (Blueprint $table) {
$table->string('host');
$table->text('robots')->nullable();
$table->timestamp('robots_cached_at');
$table->boolean('is_blocked')->default(false);
$table->integer('access_interval_sec')->default(5);
$table->timestamps();
$table->primary('host');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('content_providers');
}
}

View File

@ -11,9 +11,9 @@ class EjaculationSourcesSeeder extends Seeder
*/
public function run()
{
$sources = ['web', 'csv', 'webhook'];
$sources = ['web', 'csv'];
foreach ($sources as $source) {
DB::table('ejaculation_sources')->insertOrIgnore(['name' => $source]);
DB::table('ejaculation_sources')->insert(['name' => $source]);
}
}
}

View File

@ -1,114 +0,0 @@
openapi: 3.0.0
info:
title: Tissue API
description: |
夜のライフログサービス Tissue の公開API仕様です。
全てのAPIのURLは `https://shikorism.net/api` から始まります。
version: 0.1.0
servers:
- url: 'https://shikorism.net/api'
paths:
/webhooks/checkin/{id}:
post:
summary: /webhooks/checkin/{id}
description: Webhook IDを発行したユーザで新規チェックインを行います。
parameters:
- name: id
in: path
required: true
description: Webhook管理ページで発行したID
schema:
type: string
requestBody:
content:
application/json:
schema:
type: object
properties:
checked_in_at:
type: string
format: date-time
description: チェックイン日時 (ISO 8601形式、タイムゾーンを省略した場合も受理するが動作は未定義、省略した場合はサーバのシステム日時を使用)
tags:
type: array
items:
type: string
maxLength: 255
description: タグ (スペースを含めるのは禁止、先頭および末尾に空白が含まれている場合はtrimされる)
link:
type: string
maxLength: 2000
description: オカズリンク (http, https)
note:
type: string
maxLength: 500
description: ノート
is_private:
type: boolean
default: false
description: 非公開チェックインとして設定
is_too_sensitive:
type: boolean
default: false
description: チェックイン対象のオカズをより過激なオカズとして設定
examples:
simple:
description: 何も指定しなければ、現在時刻で公開チェックインをおこないます。
value: {}
complete:
value:
checked_in_at: 2020-07-21T19:19:19+0900
note: すごく出た
link: http://example.com
tags:
- Example
- Example_2
is_private: false
is_too_sensitive: false
responses:
200:
description: チェックイン成功
content:
application/json:
schema:
type: object
required:
- status
- checkin
properties:
status:
type: number
description: HTTPステータスコードと同じ値
example: 200
checkin:
type: object
description: チェックインデータ
422:
description: バリデーションエラー
content:
application/json:
schema:
type: object
required:
- status
- error
properties:
status:
type: number
description: HTTPステータスコードと同じ値
example: 422
error:
type: object
description: エラーデータ
required:
- message
properties:
message:
type: object
description: エラーの概要
example: Validation failed
violations:
type: string[]
description: エラーが発生した各フィールドについてのメッセージ
example:
- Checkin already exists in this time

View File

@ -8,35 +8,28 @@
"hot": "cross-env NODE_ENV=development node_modules/webpack-dev-server/bin/webpack-dev-server.js --inline --hot --config=node_modules/laravel-mix/setup/webpack.config.js",
"prod": "npm run production",
"production": "cross-env NODE_ENV=production node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js",
"eslint": "eslint --ext .js,.ts,.tsx resources/",
"stylelint": "stylelint resources/assets/sass/**/*",
"doc": "redoc-cli bundle -o public/apidoc.html openapi.yaml"
"eslint": "eslint --ext .js,.ts,.vue resources/",
"stylelint": "stylelint resources/assets/sass/**/*"
},
"devDependencies": {
"@types/bootstrap": "^4.5.0",
"@types/cal-heatmap": "^3.3.10",
"@types/chart.js": "^2.9.23",
"@types/classnames": "^2.2.10",
"@types/clipboard": "^2.0.1",
"@types/chart.js": "^2.9.22",
"@types/jquery": "^3.3.38",
"@types/js-cookie": "^2.2.0",
"@types/qs": "^6.9.4",
"@types/react": "^16.9.35",
"@types/react-dom": "^16.9.8",
"@typescript-eslint/eslint-plugin": "^3.1.0",
"@typescript-eslint/parser": "^3.1.0",
"bootstrap": "^4.5.0",
"cal-heatmap": "^3.3.10",
"chart.js": "^2.7.1",
"classnames": "^2.2.6",
"clipboard": "^2.0.6",
"cross-env": "^5.2.0",
"date-fns": "^2.15.0",
"date-fns": "^1.30.1",
"eslint": "^7.6.0",
"eslint-config-prettier": "^6.11.0",
"eslint-plugin-jquery": "^1.5.1",
"eslint-plugin-prettier": "^3.1.4",
"eslint-plugin-react": "^7.20.6",
"eslint-plugin-vue": "^6.2.2",
"husky": "^1.3.1",
"jquery": "^3.5.0",
"js-cookie": "^2.2.0",
@ -46,17 +39,18 @@
"open-iconic": "^1.1.1",
"popper.js": "^1.14.7",
"prettier": "^2.0.5",
"redoc-cli": "^0.9.8",
"qs": "^6.9.4",
"react": "^16.13.1",
"react-dom": "^16.13.1",
"resolve-url-loader": "^3.1.1",
"sass": "^1.26.8",
"sass-loader": "^7.1.0",
"stylelint": "^13.6.1",
"stylelint-config-recess-order": "^2.1.0",
"stylelint": "^9.10.1",
"stylelint-config-recess-order": "^2.0.4",
"ts-loader": "^6.0.1",
"typescript": "^3.4.5"
"typescript": "^3.4.5",
"vue": "^2.6.10",
"vue-class-component": "^7.1.0",
"vue-property-decorator": "^9.0.0",
"vue-template-compiler": "^2.6.10"
},
"stylelint": {
"extends": "stylelint-config-recess-order"
@ -71,7 +65,7 @@
"stylelint --fix",
"git add"
],
"*.{ts,tsx,js}": [
"*.{ts,js,vue}": [
"eslint --fix",
"git add"
],

View File

@ -1,4 +1,4 @@
import Cookies from 'js-cookie';
import * as Cookies from 'js-cookie';
import { fetchPostJson, fetchDeleteJson, ResponseError } from './fetch';
import { linkCard, pageSelector, deleteCheckinModal } from './tissue';

View File

@ -0,0 +1,68 @@
import Vue from 'vue';
import TagInput from './components/TagInput.vue';
import MetadataPreview from './components/MetadataPreview.vue';
import { fetchGet, ResponseError } from './fetch';
export const bus = new Vue({ name: 'EventBus' });
export enum MetadataLoadState {
Inactive,
Loading,
Success,
Failed,
}
new Vue({
el: '#app',
data: {
metadata: null,
metadataLoadState: MetadataLoadState.Inactive,
},
components: {
TagInput,
MetadataPreview,
},
mounted() {
// オカズリンクにURLがセットされている場合は、すぐにメタデータを取得する
const linkInput = this.$el.querySelector<HTMLInputElement>('#link');
if (linkInput && /^https?:\/\//.test(linkInput.value)) {
this.fetchMetadata(linkInput.value);
}
},
methods: {
// オカズリンクの変更時
onChangeLink(event: Event) {
if (event.target instanceof HTMLInputElement) {
const url = event.target.value;
if (url.trim() === '' || !/^https?:\/\//.test(url)) {
this.metadata = null;
this.metadataLoadState = MetadataLoadState.Inactive;
return;
}
this.fetchMetadata(url);
}
},
// メタデータの取得
fetchMetadata(url: string) {
this.metadataLoadState = MetadataLoadState.Loading;
fetchGet('/api/checkin/card', { url })
.then((response) => {
if (!response.ok) {
throw new ResponseError(response);
}
return response.json();
})
.then((data) => {
this.metadata = data;
this.metadataLoadState = MetadataLoadState.Success;
})
.catch(() => {
this.metadata = null;
this.metadataLoadState = MetadataLoadState.Failed;
});
},
},
});

View File

@ -1,6 +0,0 @@
import React from 'react';
import ReactDOM from 'react-dom';
import { CheckinForm } from './components/CheckinForm';
const initialState = JSON.parse(document.getElementById('initialState')?.textContent as string);
ReactDOM.render(<CheckinForm initialState={initialState} />, document.getElementById('checkinForm'));

View File

@ -1,25 +0,0 @@
import React from 'react';
type CheckboxProps = {
id: string;
name: string;
className?: string;
checked?: boolean;
onChange?: (newValue: boolean) => void;
};
export const CheckBox: React.FC<CheckboxProps> = ({ id, name, className, checked, onChange, children }) => (
<div className={`custom-control custom-checkbox ${className}`}>
<input
id={id}
name={name}
type="checkbox"
className="custom-control-input"
checked={checked}
onChange={(e) => onChange && onChange(e.target.checked)}
/>
<label className="custom-control-label" htmlFor={id}>
{children}
</label>
</div>
);

View File

@ -1,149 +0,0 @@
import React, { useState } from 'react';
import classNames from 'classnames';
import { CheckBox } from './CheckBox';
import { FieldError, StandaloneFieldError } from './FieldError';
import { TagInput } from './TagInput';
import { MetadataPreview } from './MetadataPreview';
type CheckinFormProps = {
initialState: any;
};
export const CheckinForm: React.FC<CheckinFormProps> = ({ initialState }) => {
const [date, setDate] = useState<string>(initialState.fields.date || '');
const [time, setTime] = useState<string>(initialState.fields.time || '');
const [tags, setTags] = useState<string[]>(initialState.fields.tags || []);
const [link, setLink] = useState<string>(initialState.fields.link || '');
const [linkForPreview, setLinkForPreview] = useState(link);
const [note, setNote] = useState<string>(initialState.fields.note || '');
const [isPrivate, setPrivate] = useState<boolean>(!!initialState.fields.is_private);
const [isTooSensitive, setTooSensitive] = useState<boolean>(!!initialState.fields.is_too_sensitive);
return (
<>
<div className="form-row">
<div className="form-group col-sm-6">
<label htmlFor="date">
<span className="oi oi-calendar" />
</label>
<input
type="text"
id="date"
name="date"
className={classNames({
'form-control': true,
'is-invalid': initialState.errors?.date || initialState.errors?.datetime,
})}
pattern="^20[0-9]{2}/(0[1-9]|1[0-2])/(0[1-9]|[12][0-9]|3[01])$"
required
value={date}
onChange={(e) => setDate(e.target.value)}
/>
<FieldError errors={initialState.errors?.date} />
</div>
<div className="form-group col-sm-6">
<label htmlFor="time">
<span className="oi oi-clock" />
</label>
<input
type="text"
id="time"
name="time"
className={classNames({
'form-control': true,
'is-invalid': initialState.errors?.time || initialState.errors?.datetime,
})}
pattern="^([01][0-9]|2[0-3]):[0-5][0-9]$"
required
value={time}
onChange={(e) => setTime(e.target.value)}
/>
<FieldError errors={initialState.errors?.time} />
</div>
<StandaloneFieldError errors={initialState.errors?.datetime} />
</div>
<div className="form-row">
<div className="form-group col-sm-12">
<label htmlFor="tagInput">
<span className="oi oi-tags" />
</label>
<TagInput
id="tagInput"
name="tags"
values={tags}
isInvalid={!!initialState.errors?.tags}
onChange={(v) => setTags(v)}
/>
<small className="form-text text-muted">Tab, Enter, </small>
<FieldError errors={initialState.errors?.tags} />
</div>
</div>
<div className="form-row">
<div className="form-group col-sm-12">
<label htmlFor="link">
<span className="oi oi-link-intact" />
</label>
<input
type="text"
id="link"
name="link"
autoComplete="off"
className={classNames({ 'form-control': true, 'is-invalid': initialState.errors?.link })}
placeholder="http://..."
value={link}
onChange={(e) => setLink(e.target.value)}
onBlur={() => setLinkForPreview(link)}
/>
<small className="form-text text-muted">URLを貼り付けて登録することができます</small>
<FieldError errors={initialState.errors?.link} />
</div>
</div>
<MetadataPreview link={linkForPreview} tags={tags} onClickTag={(v) => setTags(tags.concat(v))} />
<div className="form-row">
<div className="form-group col-sm-12">
<label htmlFor="note">
<span className="oi oi-comment-square" />
</label>
<textarea
id="note"
name="note"
className={classNames({ 'form-control': true, 'is-invalid': initialState.errors?.note })}
rows={4}
value={note}
onChange={(e) => setNote(e.target.value)}
/>
<small className="form-text text-muted"> 500 </small>
<FieldError errors={initialState.errors?.note} />
</div>
</div>
<div className="form-row mt-4">
<p></p>
<div className="form-group col-sm-12">
<CheckBox
id="isPrivate"
name="is_private"
className="mb-3"
checked={isPrivate}
onChange={(v) => setPrivate(v)}
>
<span className="oi oi-lock-locked" />
</CheckBox>
<CheckBox
id="isTooSensitive"
name="is_too_sensitive"
className="mb-3"
checked={isTooSensitive}
onChange={(v) => setTooSensitive(v)}
>
<span className="oi oi-warning" />
</CheckBox>
</div>
</div>
<div className="text-center">
<button className="btn btn-primary" type="submit">
</button>
</div>
</>
);
};

View File

@ -1,16 +0,0 @@
import React from 'react';
type FieldErrorProps = {
errors?: string[];
};
export const FieldError: React.FC<FieldErrorProps> = ({ errors }) =>
(errors && errors.length > 0 && <div className="invalid-feedback">{errors[0]}</div>) || null;
export const StandaloneFieldError: React.FC<FieldErrorProps> = ({ errors }) =>
(errors && errors.length > 0 && (
<div className="form-group col-sm-12" style={{ marginTop: '-1rem' }}>
<small className="text-danger">{errors[0]}</small>
</div>
)) ||
null;

View File

@ -1,157 +0,0 @@
import React, { useEffect, useState } from 'react';
import classNames from 'classnames';
import { fetchGet, ResponseError } from '../fetch';
enum MetadataLoadState {
Inactive,
Loading,
Success,
Failed,
}
type Metadata = {
url: string;
title: string;
description: string;
image: string;
expires_at: string | null;
tags: {
name: string;
}[];
};
type Suggestion = {
name: string;
used: boolean;
};
type MetadataPreviewProps = {
link: string;
tags: string[];
onClickTag: (tag: string) => void;
};
const MetadataLoading = () => (
<div className="row no-gutters">
<div className="col-12">
<div className="card-body">
<h6 className="card-title text-center font-weight-bold text-info">
<span className="oi oi-loop-circular" />
</h6>
</div>
</div>
</div>
);
const MetadataLoadFailed = () => (
<div className="row no-gutters">
<div className="col-12">
<div className="card-body">
<h6 className="card-title text-center font-weight-bold text-danger">
<span className="oi oi-circle-x" />
</h6>
</div>
</div>
</div>
);
export const MetadataPreview: React.FC<MetadataPreviewProps> = ({ link, tags, onClickTag }) => {
const [state, setState] = useState(MetadataLoadState.Inactive);
const [metadata, setMetadata] = useState<Metadata | null>(null);
useEffect(() => {
if (link.trim() === '' || !/^https?:\/\//.test(link)) {
setState(MetadataLoadState.Inactive);
setMetadata(null);
return;
}
setState(MetadataLoadState.Loading);
fetchGet('/api/checkin/card', { url: link })
.then((response) => {
if (!response.ok) {
throw new ResponseError(response);
}
return response.json();
})
.then((data) => {
setState(MetadataLoadState.Success);
setMetadata(data);
})
.catch(() => {
setState(MetadataLoadState.Failed);
setMetadata(null);
});
}, [link]);
if (state === MetadataLoadState.Inactive) {
return null;
}
const hasImage = metadata !== null && metadata.image !== '';
const descClasses = classNames({
'col-8': hasImage,
'col-12': !hasImage,
});
const tagClasses = (s: Suggestion) =>
classNames({
'list-inline-item': true,
badge: true,
'badge-primary': !s.used,
'badge-secondary': s.used,
'metadata-tag-item': true,
});
const suggestions =
metadata?.tags.map((t) => ({
name: t.name,
used: tags.indexOf(t.name) !== -1,
})) ?? [];
return (
<div className="form-row">
<div className="form-group col-sm-12">
<div className="card tis-metadata-preview-link-card mb-2 px-0">
{state === MetadataLoadState.Loading ? (
<MetadataLoading />
) : state === MetadataLoadState.Success ? (
<div className="row no-gutters">
{hasImage && (
<div className="col-4 justify-content-center align-items-center">
<img src={metadata?.image} alt="Thumbnail" className="w-100 bg-secondary" />
</div>
)}
<div className={descClasses}>
<div className="card-body">
<h6 className="card-title font-weight-bold">{metadata?.title}</h6>
{suggestions.length > 0 && (
<>
<p className="card-text mb-2">
<br />
<span className="text-secondary">
()
</span>
</p>
<ul className="list-inline d-inline">
{suggestions.map((tag) => (
<li
key={tag.name}
className={tagClasses(tag)}
onClick={() => onClickTag(tag.name)}
>
<span className="oi oi-tag" /> {tag.name}
</li>
))}
</ul>
</>
)}
</div>
</div>
</div>
) : (
<MetadataLoadFailed />
)}
</div>
</div>
</div>
);
};

View File

@ -0,0 +1,156 @@
<template>
<div class="form-row" v-if="state !== MetadataLoadState.Inactive">
<div class="form-group col-sm-12">
<div class="card link-card-mini mb-2 px-0">
<div v-if="state === MetadataLoadState.Loading" class="row no-gutters">
<div class="col-12">
<div class="card-body">
<h6 class="card-title text-center font-weight-bold text-info" style="font-size: small;">
<span class="oi oi-loop-circular"></span> オカズの情報を読み込んでいます
</h6>
</div>
</div>
</div>
<div v-else-if="state === MetadataLoadState.Success" class="row no-gutters">
<div v-if="hasImage" class="col-4 justify-content-center align-items-center">
<img :src="metadata.image" alt="Thumbnail" class="w-100 bg-secondary" />
</div>
<div :class="descClasses">
<div class="card-body">
<h6 class="card-title font-weight-bold" style="font-size: small;">{{ metadata.title }}</h6>
<template v-if="suggestions.length > 0">
<p class="card-text mb-2" style="font-size: small;">
タグ候補<br /><span class="text-secondary"
>(クリックするとタグ入力欄にコピーできます)</span
>
</p>
<ul class="list-inline d-inline">
<li
v-for="tag in suggestions"
:class="tagClasses(tag)"
@click="addTag(tag.name)"
:key="tag.name"
>
<span class="oi oi-tag"></span> {{ tag.name }}
</li>
</ul>
</template>
</div>
</div>
</div>
<div v-else class="row no-gutters">
<div class="col-12">
<div class="card-body">
<h6 class="card-title text-center font-weight-bold text-danger" style="font-size: small;">
<span class="oi oi-circle-x"></span> オカズの情報を読み込めませんでした
</h6>
</div>
</div>
</div>
</div>
</div>
</div>
</template>
<script lang="ts">
import { Vue, Component, Prop } from 'vue-property-decorator';
import { bus, MetadataLoadState } from '../checkin';
type Metadata = {
url: string;
title: string;
description: string;
image: string;
expires_at: string | null;
tags: {
name: string;
}[];
};
type Suggestion = {
name: string;
used: boolean;
};
@Component
export default class MetadataPreview extends Vue {
@Prop() readonly state!: MetadataLoadState;
@Prop() readonly metadata!: Metadata | null;
// for use in v-if
private readonly MetadataLoadState = MetadataLoadState;
tags: string[] = [];
created(): void {
bus.$on('change-tag', (tags: string[]) => (this.tags = tags));
bus.$emit('resend-tag');
}
addTag(tag: string): void {
bus.$emit('add-tag', tag);
}
tagClasses(s: Suggestion) {
return {
'list-inline-item': true,
badge: true,
'badge-primary': !s.used,
'badge-secondary': s.used,
'metadata-tag-item': true,
};
}
get suggestions(): Suggestion[] {
if (this.metadata === null) {
return [];
}
return this.metadata.tags.map((t) => {
return {
name: t.name,
used: this.tags.indexOf(t.name) !== -1,
};
});
}
get hasImage() {
return this.metadata !== null && this.metadata.image !== '';
}
get descClasses() {
return {
'col-8': this.hasImage,
'col-12': !this.hasImage,
};
}
}
</script>
<style lang="scss" scoped>
.link-card-mini {
$height: 150px;
overflow: hidden;
.row > div:first-child {
display: flex;
&:not([display='none']) {
min-height: $height;
img {
position: absolute;
}
}
}
.card-text {
white-space: pre-line;
}
}
.metadata-tag-item {
cursor: pointer;
user-select: none;
}
</style>

View File

@ -1,75 +0,0 @@
import React, { useState, useRef } from 'react';
import classNames from 'classnames';
type TagInputProps = {
id: string;
name: string;
values: string[];
isInvalid: boolean;
onChange?: (newValues: string[]) => void;
};
export const TagInput: React.FC<TagInputProps> = ({ id, name, values, isInvalid, onChange }) => {
const [buffer, setBuffer] = useState('');
const containerClass = classNames('form-control', 'h-auto', { 'is-invalid': isInvalid });
const inputRef = useRef<HTMLInputElement>(null);
const removeTag = (index: number) => {
onChange && onChange(values.filter((v, i) => i != index));
};
const onKeyDown = (event: React.KeyboardEvent<HTMLInputElement>) => {
if (buffer.trim() !== '') {
switch (event.key) {
case 'Tab':
case 'Enter':
case ' ':
if ((event as any).isComposing !== true) {
onChange && onChange(values.concat(buffer.trim().replace(/\s+/g, '_')));
setBuffer('');
}
event.preventDefault();
break;
case 'Unidentified': {
// 実際にテキストボックスに入力されている文字を見に行く (フォールバック処理)
const nativeEvent = event.nativeEvent;
if (nativeEvent.srcElement && (nativeEvent.srcElement as HTMLInputElement).value.slice(-1) == ' ') {
onChange && onChange(values.concat(buffer.trim().replace(/\s+/g, '_')));
setBuffer('');
event.preventDefault();
}
break;
}
}
} else if (event.key === 'Enter') {
// 誤爆防止
event.preventDefault();
}
};
return (
<div className={containerClass} onClick={() => inputRef.current?.focus()}>
<input name={name} type="hidden" value={values.join(' ')} />
<ul className="list-inline d-inline">
{values.map((tag, i) => (
<li
key={i}
className={classNames('list-inline-item', 'badge', 'badge-primary', 'tis-tag-input-item')}
onClick={() => removeTag(i)}
>
<span className="oi oi-tag" /> {tag} | x
</li>
))}
<li className="list-inline-item">
<input
id={id}
ref={inputRef}
type="text"
className="tis-tag-input-field"
value={buffer}
onChange={(e) => setBuffer(e.target.value)}
onKeyDown={onKeyDown}
/>
</li>
</ul>
</div>
);
};

View File

@ -0,0 +1,96 @@
<template>
<div :class="containerClass" @click="$refs.input.focus()">
<input :name="name" type="hidden" :value="tagValue" />
<ul class="list-inline d-inline">
<li
v-for="(tag, i) in tags"
class="list-inline-item badge badge-primary tag-item"
@click="removeTag(i)"
:key="tag"
>
<span class="oi oi-tag"></span> {{ tag }} | x
</li>
</ul>
<input :id="id" ref="input" type="text" class="tag-input" v-model="buffer" @keydown="onKeyDown" />
</div>
</template>
<script lang="ts">
import { Vue, Component, Prop, Watch } from 'vue-property-decorator';
import { bus } from '../checkin';
@Component
export default class TagInput extends Vue {
@Prop(String) readonly id!: string;
@Prop(String) readonly name!: string;
@Prop(String) readonly value!: string;
@Prop(Boolean) readonly isInvalid!: boolean;
tags: string[] = this.value.trim() !== '' ? this.value.trim().split(' ') : [];
buffer = '';
created() {
bus.$on('add-tag', (tag: string) => this.tags.indexOf(tag) === -1 && this.tags.push(tag));
bus.$on('resend-tag', () => bus.$emit('change-tag', this.tags));
}
onKeyDown(event: KeyboardEvent) {
if (this.buffer.trim() !== '') {
switch (event.key) {
case 'Tab':
case 'Enter':
case ' ':
if ((event as any).isComposing !== true) {
this.tags.push(this.buffer.trim().replace(/\s+/g, '_'));
this.buffer = '';
}
event.preventDefault();
break;
case 'Unidentified':
// ()
if (event.srcElement && (event.srcElement as HTMLInputElement).value.slice(-1) == ' ') {
this.tags.push(this.buffer.trim().replace(/\s+/g, '_'));
this.buffer = '';
event.preventDefault();
}
break;
}
} else if (event.key === 'Enter') {
//
event.preventDefault();
}
}
removeTag(index: number) {
this.tags.splice(index, 1);
}
@Watch('tags')
onTagsChanged() {
bus.$emit('change-tag', this.tags);
}
get containerClass() {
return {
'form-control': true,
'h-auto': true,
'is-invalid': this.isInvalid,
};
}
get tagValue(): string {
return this.tags.join(' ');
}
}
</script>
<style lang="scss" scoped>
.tag-item {
cursor: pointer;
}
.tag-input {
border: 0;
outline: 0;
}
</style>

View File

@ -1,4 +1,4 @@
import Chart from 'chart.js';
import * as Chart from 'chart.js';
const graph = document.getElementById('global-count-graph') as HTMLCanvasElement;
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion

View File

@ -1,32 +0,0 @@
import ClipboardJS from 'clipboard';
$('.webhook-url').on('focus', function () {
$(this).trigger('select');
});
new ClipboardJS('.copy-to-clipboard', {
target(elem: Element): Element {
return elem.parentElement?.parentElement?.querySelector('.webhook-url') as Element;
},
}).on('success', (e) => {
e.clearSelection();
$(e.trigger).popover('show');
});
$('.copy-to-clipboard').on('shown.bs.popover', function () {
setTimeout(() => $(this).popover('hide'), 3000);
});
const deleteModal = document.getElementById('deleteIncomingWebhookModal');
if (deleteModal) {
let id: any = null;
deleteModal.querySelector('form')?.addEventListener('submit', function () {
this.action = this.action.replace('@', id);
});
document.querySelectorAll<HTMLElement>('[data-target="#deleteIncomingWebhookModal"]').forEach((el) => {
el.addEventListener('click', function (e) {
e.preventDefault();
id = this.dataset.id;
$(deleteModal).modal('show', this);
});
});
}

View File

@ -1,4 +1,4 @@
import CalHeatMap from 'cal-heatmap';
import * as CalHeatMap from 'cal-heatmap';
import { subMonths } from 'date-fns';
if (document.getElementById('cal-heatmap')) {

View File

@ -1,5 +1,5 @@
import CalHeatMap from 'cal-heatmap';
import Chart from 'chart.js';
import * as CalHeatMap from 'cal-heatmap';
import * as Chart from 'chart.js';
import { addMonths, format } from 'date-fns';
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
@ -90,7 +90,7 @@ function createMonthlyGraphData(from: Date) {
for (let i = 0; i < 12; i++) {
const current = addMonths(from, i);
const yearAndMonth = format(current, 'yyyy/MM');
const yearAndMonth = format(current, 'YYYY/MM');
keys.push(yearAndMonth);
values.push(graphData.monthlySum[yearAndMonth] || 0);
}

View File

@ -13,8 +13,6 @@ $primary: #e53fb1;
// Components
@import "components/ejaculation";
@import "components/link-card";
@import "components/tag-input";
@import "components/metadata-preview";
// Tag
@import "tag/index";

View File

@ -1,32 +0,0 @@
.tis-metadata-preview {
&-link-card {
$height: 150px;
overflow: hidden;
.row > div:first-child {
display: flex;
&:not([display='none']) {
min-height: $height;
img {
position: absolute;
}
}
}
.card-title {
font-size: small;
}
.card-text {
font-size: small;
white-space: pre-line;
}
}
&-tag-item {
cursor: pointer;
user-select: none;
}
}

View File

@ -1,11 +0,0 @@
.tis-tag-input {
&-item {
cursor: pointer;
}
&-field {
border: 0;
outline: 0;
}
}

View File

@ -6,19 +6,14 @@
</h5>
</div>
<!-- tags -->
@if ($ejaculation->is_private || $ejaculation->source !== 'web' || $ejaculation->tags->isNotEmpty())
@if ($ejaculation->is_private || $ejaculation->source === 'csv' || $ejaculation->tags->isNotEmpty())
<p class="mb-2">
@if ($ejaculation->is_private)
<span class="badge badge-warning"><span class="oi oi-lock-locked"></span> 非公開</span>
@endif
@switch ($ejaculation->source)
@case ('csv')
<span class="badge badge-info"><span class="oi oi-cloud-upload"></span> インポート</span>
@break
@case ('webhook')
<span class="badge badge-info" data-toggle="tooltip" title="Webhookからチェックイン"><span class="oi oi-flash"></span></span>
@break
@endswitch
@if ($ejaculation->source === 'csv')
<span class="badge badge-info"><span class="oi oi-cloud-upload"></span> インポート</span>
@endif
@foreach ($ejaculation->tags as $tag)
<a class="badge badge-secondary" href="{{ route('search', ['q' => $tag->name]) }}"><span class="oi oi-tag"></span> {{ $tag->name }}</a>
@endforeach

View File

@ -3,15 +3,99 @@
@section('title', 'チェックイン')
@section('content')
<div class="container">
<div id="app" class="container">
<h2>今致してる?</h2>
<hr>
<div class="row justify-content-center mt-5">
<div class="col-lg-6">
<form method="post" action="{{ route('checkin') }}">
{{ csrf_field() }}
<div id="checkinForm">
<div class="text-center small" style="height: 640px;">しばらくお待ちください…</div>
<div class="form-row">
<div class="form-group col-sm-6">
<label for="date"><span class="oi oi-calendar"></span> 日付</label>
<input id="date" name="date" type="text" class="form-control {{ $errors->has('date') || $errors->has('datetime') ? ' is-invalid' : '' }}"
pattern="^20[0-9]{2}/(0[1-9]|1[0-2])/(0[1-9]|[12][0-9]|3[01])$" value="{{ old('date') ?? $defaults['date'] }}" required>
@if ($errors->has('date'))
<div class="invalid-feedback">{{ $errors->first('date') }}</div>
@endif
</div>
<div class="form-group col-sm-6">
<label for="time"><span class="oi oi-clock"></span> 時刻</label>
<input id="time" name="time" type="text" class="form-control {{ $errors->has('time') || $errors->has('datetime') ? ' is-invalid' : '' }}"
pattern="^([01][0-9]|2[0-3]):[0-5][0-9]$" value="{{ old('time') ?? $defaults['time'] }}" required>
@if ($errors->has('time'))
<div class="invalid-feedback">{{ $errors->first('time') }}</div>
@endif
</div>
@if ($errors->has('datetime'))
<div class="form-group col-sm-12" style="margin-top: -1rem;">
<small class="text-danger">{{ $errors->first('datetime') }}</small>
</div>
@endif
</div>
<div class="form-row">
<div class="form-group col-sm-12">
<label for="tagInput"><span class="oi oi-tags"></span> タグ</label>
<tag-input id="tagInput" name="tags" value="{{ old('tags') ?? $defaults['tags'] }}" :is-invalid="{{ $errors->has('tags') ? 'true' : 'false' }}"></tag-input>
<small class="form-text text-muted">
Tab, Enter, 半角スペースのいずれかで入力確定します。
</small>
@if ($errors->has('tags'))
<div class="invalid-feedback">{{ $errors->first('tags') }}</div>
@endif
</div>
</div>
<div class="form-row">
<div class="form-group col-sm-12">
<label for="link"><span class="oi oi-link-intact"></span> オカズリンク</label>
<input id="link" name="link" type="text" autocomplete="off" class="form-control {{ $errors->has('link') ? ' is-invalid' : '' }}"
placeholder="http://..." value="{{ old('link') ?? $defaults['link'] }}"
@change="onChangeLink">
<small class="form-text text-muted">
オカズのURLを貼り付けて登録することができます。
</small>
@if ($errors->has('link'))
<div class="invalid-feedback">{{ $errors->first('link') }}</div>
@endif
</div>
</div>
<metadata-preview :metadata="metadata" :state="metadataLoadState"></metadata-preview>
<div class="form-row">
<div class="form-group col-sm-12">
<label for="note"><span class="oi oi-comment-square"></span> ノート</label>
<textarea id="note" name="note" class="form-control {{ $errors->has('note') ? ' is-invalid' : '' }}" rows="4">{{ old('note') ?? $defaults['note'] }}</textarea>
<small class="form-text text-muted">
最大 500 文字
</small>
@if ($errors->has('note'))
<div class="invalid-feedback">{{ $errors->first('note') }}</div>
@endif
</div>
</div>
<div class="form-row mt-4">
<p>オプション</p>
<div class="form-group col-sm-12">
<div class="custom-control custom-checkbox mb-3">
<input id="isPrivate" name="is_private" type="checkbox" class="custom-control-input" {{ old('is_private') || $defaults['is_private'] ? 'checked' : '' }}>
<label class="custom-control-label" for="isPrivate">
<span class="oi oi-lock-locked"></span> このチェックインを非公開にする
</label>
</div>
<div class="custom-control custom-checkbox mb-3">
<input id="isTooSensitive" name="is_too_sensitive" type="checkbox" class="custom-control-input" {{ old('is_too_sensitive') || $defaults['is_too_sensitive'] ? 'checked' : '' }}>
<label class="custom-control-label" for="isTooSensitive">
<span class="oi oi-warning"></span> チェックイン対象のオカズをより過激なオカズとして設定する
</label>
</div>
</div>
</div>
<div class="text-center">
<button class="btn btn-primary" type="submit">チェックイン</button>
</div>
</form>
<p class="text-center small mt-4"><strong>Tips</strong>: ブックマークレットや共有機能で、簡単にチェックインできます! <a href="{{ route('checkin.tools') }}" target="_blank" rel="noopener">使い方はこちら</a></p>
@ -21,6 +105,5 @@
@endsection
@push('script')
<script id="initialState" type="application/json">@json($initialState)</script>
<script src="{{ mix('js/checkin.js') }}"></script>
@endpush

View File

@ -3,7 +3,7 @@
@section('title', 'チェックインの修正')
@section('content')
<div class="container">
<div id="app" class="container">
<h2>チェックインの修正</h2>
<hr>
<div class="row justify-content-center mt-5">
@ -11,8 +11,92 @@
<form method="post" action="{{ route('checkin.update', ['id' => $ejaculation->id]) }}">
{{ method_field('PUT') }}
{{ csrf_field() }}
<div id="checkinForm">
<div class="text-center small" style="height: 640px;">しばらくお待ちください…</div>
<div class="form-row">
<div class="form-group col-sm-6">
<label for="date"><span class="oi oi-calendar"></span> 日付</label>
<input id="date" name="date" type="text" class="form-control {{ $errors->has('date') || $errors->has('datetime') ? ' is-invalid' : '' }}"
pattern="^20[0-9]{2}/(0[1-9]|1[0-2])/(0[1-9]|[12][0-9]|3[01])$" value="{{ old('date') ?? $ejaculation->ejaculated_date->format('Y/m/d') }}" required>
@if ($errors->has('date'))
<div class="invalid-feedback">{{ $errors->first('date') }}</div>
@endif
</div>
<div class="form-group col-sm-6">
<label for="time"><span class="oi oi-clock"></span> 時刻</label>
<input id="time" name="time" type="text" class="form-control {{ $errors->has('time') || $errors->has('datetime') ? ' is-invalid' : '' }}"
pattern="^([01][0-9]|2[0-3]):[0-5][0-9]$" value="{{ old('time') ?? $ejaculation->ejaculated_date->format('H:i') }}" required>
@if ($errors->has('time'))
<div class="invalid-feedback">{{ $errors->first('time') }}</div>
@endif
</div>
@if ($errors->has('datetime'))
<div class="form-group col-sm-12" style="margin-top: -1rem;">
<small class="text-danger">{{ $errors->first('datetime') }}</small>
</div>
@endif
</div>
<div class="form-row">
<div class="form-group col-sm-12">
<label for="tagInput"><span class="oi oi-tags"></span> タグ</label>
<tag-input id="tagInput" name="tags" value="{{ old('tags') ?? $ejaculation->textTags() }}" :is-invalid="{{ $errors->has('tags') ? 'true' : 'false' }}"></tag-input>
<small class="form-text text-muted">
Tab, Enter, 半角スペースのいずれかで入力確定します。
</small>
@if ($errors->has('tags'))
<div class="invalid-feedback">{{ $errors->first('tags') }}</div>
@endif
</div>
</div>
<div class="form-row">
<div class="form-group col-sm-12">
<label for="link"><span class="oi oi-link-intact"></span> オカズリンク</label>
<input id="link" name="link" type="text" autocomplete="off" class="form-control {{ $errors->has('link') ? ' is-invalid' : '' }}"
placeholder="http://..." value="{{ old('link') ?? $ejaculation->link }}"
@change="onChangeLink">
<small class="form-text text-muted">
オカズのURLを貼り付けて登録することができます。
</small>
@if ($errors->has('link'))
<div class="invalid-feedback">{{ $errors->first('link') }}</div>
@endif
</div>
</div>
<metadata-preview :metadata="metadata" :state="metadataLoadState"></metadata-preview>
<div class="form-row">
<div class="form-group col-sm-12">
<label for="note"><span class="oi oi-comment-square"></span> ノート</label>
<textarea id="note" name="note" class="form-control {{ $errors->has('note') ? ' is-invalid' : '' }}" rows="4">{{ old('note') ?? $ejaculation->note }}</textarea>
<small class="form-text text-muted">
最大 500 文字
</small>
@if ($errors->has('note'))
<div class="invalid-feedback">{{ $errors->first('note') }}</div>
@endif
</div>
</div>
<div class="form-row mt-4">
<p>オプション</p>
<div class="form-group col-sm-12">
<div class="custom-control custom-checkbox mb-3">
<input id="isPrivate" name="is_private" type="checkbox" class="custom-control-input" {{ (is_bool(old('is_private')) ? old('is_private') : $ejaculation->is_private) ? 'checked' : '' }}>
<label class="custom-control-label" for="isPrivate">
<span class="oi oi-lock-locked"></span> このチェックインを非公開にする
</label>
</div>
<div class="custom-control custom-checkbox mb-3">
<input id="isTooSensitive" name="is_too_sensitive" type="checkbox" class="custom-control-input" {{ (is_bool(old('is_too_sensitive')) ? old('is_too_sensitive') : $ejaculation->is_too_sensitive) ? 'checked' : '' }}>
<label class="custom-control-label" for="isTooSensitive">
<span class="oi oi-warning"></span> チェックイン対象のオカズをより過激なオカズとして設定する
</label>
</div>
</div>
</div>
<div class="text-center">
<button class="btn btn-primary" type="submit">チェックイン</button>
</div>
</form>
</div>
@ -21,6 +105,5 @@
@endsection
@push('script')
<script id="initialState" type="application/json">@json($initialState)</script>
<script src="{{ mix('js/checkin.js') }}"></script>
@endpush

View File

@ -34,19 +34,14 @@
<h5>{{ $ejaculatedSpan ?? '精通' }} <small class="text-muted">{{ $ejaculation->before_date }}{{ !empty($ejaculation->before_date) ? ' ' : '' }}{{ $ejaculation->ejaculated_date->format('Y/m/d H:i') }}</small></h5>
</div>
<!-- tags -->
@if ($ejaculation->is_private || $ejaculation->source !== 'web' || $ejaculation->tags->isNotEmpty())
@if ($ejaculation->is_private || $ejaculation->source === 'csv' || $ejaculation->tags->isNotEmpty())
<p class="mb-2">
@if ($ejaculation->is_private)
<span class="badge badge-warning"><span class="oi oi-lock-locked"></span> 非公開</span>
@endif
@switch ($ejaculation->source)
@case ('csv')
<span class="badge badge-info"><span class="oi oi-cloud-upload"></span> インポート</span>
@break
@case ('webhook')
<span class="badge badge-info" data-toggle="tooltip" title="Webhookからチェックイン"><span class="oi oi-flash"></span></span>
@break
@endswitch
@if ($ejaculation->source === 'csv')
<span class="badge badge-info"><span class="oi oi-cloud-upload"></span> インポート</span>
@endif
@foreach ($ejaculation->tags as $tag)
<a class="badge badge-secondary" href="{{ route('search', ['q' => $tag->name]) }}"><span class="oi oi-tag"></span> {{ $tag->name }}</a>
@endforeach

View File

@ -10,8 +10,6 @@
href="{{ route('setting') }}"><span class="oi oi-person mr-1"></span> プロフィール</a>
<a class="list-group-item list-group-item-action {{ Route::currentRouteName() === 'setting.privacy' ? 'active' : '' }}"
href="{{ route('setting.privacy') }}"><span class="oi oi-shield mr-1"></span> プライバシー</a>
<a class="list-group-item list-group-item-action {{ Route::currentRouteName() === 'setting.webhooks' ? 'active' : '' }}"
href="{{ route('setting.webhooks') }}"><span class="oi oi-link-intact mr-1"></span> Webhook</a>
<a class="list-group-item list-group-item-action {{ Route::currentRouteName() === 'setting.import' ? 'active' : '' }}"
href="{{ route('setting.import') }}"><span class="oi oi-data-transfer-upload mr-1"></span> データのインポート</a>
<a class="list-group-item list-group-item-action {{ Route::currentRouteName() === 'setting.export' ? 'active' : '' }}"

View File

@ -1,70 +0,0 @@
@extends('setting.base')
@section('title', 'Webhook')
@section('tab-content')
<h3>Incoming Webhook</h3>
<hr>
<p>さまざまなシステムと連携してチェックインを行うためのWebhook URLを作成することができます。APIドキュメントは<a href="{{ url('/apidoc.html') }}">こちら</a>から参照いただけます。</p>
<h4>新規作成</h4>
<div class="card mt-3">
<div class="card-body">
<h6 class="font-weight-bold">おことわり</h6>
<p>Webhook APIは予告なく仕様変更を行う場合がございます。また、サーバに対する過剰なリクエストや、不審な公開チェックインを繰り返している場合には管理者の裁量によって予告なく無効化(削除)する場合があります。</p>
<p>通常利用と同様、1分以内のチェックインは禁止されていることを考慮してください。また、テスト目的であれば非公開チェックインをご活用ください。</p>
<hr>
@if (count($webhooks) >= $webhooksLimit)
<p class="my-0 text-danger">1ユーザーが作成可能なWebhookは、{{ $webhooksLimit }}件までに制限されています。</p>
@else
<form action="{{ route('setting.webhooks.store') }}" method="post">
{{ csrf_field() }}
<div class="form-group">
<label for="name">名前 (メモ)</label>
<input id="name" class="form-control {{ $errors->has('name') ? ' is-invalid' : '' }}" name="name" type="text" required>
<small class="form-text text-muted">後で分かるように名前を付けておいてください。</small>
@if ($errors->has('name'))
<div class="invalid-feedback">{{ $errors->first('name') }}</div>
@endif
</div>
<button class="btn btn-primary" type="submit">新規作成</button>
</form>
@endif
</div>
</div>
@if (!$webhooks->isEmpty())
<h4 class="mt-4">作成済みのWebhook</h4>
<div class="list-group mt-3">
@foreach ($webhooks as $webhook)
<div class="list-group-item d-flex justify-content-between align-items-center">
<div class="flex-grow-1 mr-2">
<div>{{ $webhook->name }}</div>
<input class="webhook-url form-control form-control-sm mt-1" type="text" value="{{ url('/api/webhooks/checkin/' . $webhook->id) }}" readonly>
</div>
<div class="ml-2">
<button class="btn btn-outline-secondary copy-to-clipboard" type="button" data-toggle="popover" data-trigger="manual" data-placement="top" data-content="コピーしました!">コピー</button>
<button class="btn btn-outline-danger" type="button" data-target="#deleteIncomingWebhookModal" data-id="{{ $webhook->id }}">削除</button>
</div>
</div>
@endforeach
</div>
@endif
@component('components.modal', ['id' => 'deleteIncomingWebhookModal'])
@slot('title')
削除確認
@endslot
Webhookを削除してもよろしいですか
@slot('footer')
<form action="{{ route('setting.webhooks.destroy', ['webhook' => '@']) }}" method="post">
{{ csrf_field() }}
{{ method_field('DELETE') }}
<button type="button" class="btn btn-secondary" data-dismiss="modal">キャンセル</button>
<button type="submit" class="btn btn-danger">削除</button>
</form>
@endslot
@endcomponent
@endsection
@push('script')
<script src="{{ mix('js/setting/webhooks.js') }}"></script>
@endpush

View File

@ -51,19 +51,14 @@
<h5>{{ $ejaculation->ejaculated_span ?? '精通' }} <a href="{{ route('checkin.show', ['id' => $ejaculation->id]) }}" class="text-muted"><small>{{ $ejaculation->before_date }}{{ !empty($ejaculation->before_date) ? ' ' : '' }}{{ $ejaculation->ejaculated_date->format('Y/m/d H:i') }}</small></a></h5>
</div>
<!-- tags -->
@if ($ejaculation->is_private || $ejaculation->source !== 'web' || $ejaculation->tags->isNotEmpty())
@if ($ejaculation->is_private || $ejaculation->source === 'csv' || $ejaculation->tags->isNotEmpty())
<p class="mb-2">
@if ($ejaculation->is_private)
<span class="badge badge-warning"><span class="oi oi-lock-locked"></span> 非公開</span>
@endif
@switch ($ejaculation->source)
@case ('csv')
<span class="badge badge-info"><span class="oi oi-cloud-upload"></span> インポート</span>
@break
@case ('webhook')
<span class="badge badge-info" data-toggle="tooltip" title="Webhookからチェックイン"><span class="oi oi-flash"></span></span>
@break
@endswitch
@if ($ejaculation->source === 'csv')
<span class="badge badge-info"><span class="oi oi-cloud-upload"></span> インポート</span>
@endif
@foreach ($ejaculation->tags as $tag)
<a class="badge badge-secondary" href="{{ route('search', ['q' => $tag->name]) }}"><span class="oi oi-tag"></span> {{ $tag->name }}</a>
@endforeach

View File

@ -15,13 +15,9 @@
// return $request->user();
//});
Route::get('/checkin/card', 'Api\\CardController@show')
->middleware('throttle:180,1,card');
Route::get('/checkin/card', 'Api\\CardController@show');
Route::middleware(['throttle:60,1', 'stateful', 'auth'])->group(function () {
Route::middleware('auth')->group(function () {
Route::post('/likes', 'Api\\LikeController@store');
Route::delete('/likes/{id}', 'Api\\LikeController@destroy');
});
Route::post('/webhooks/checkin/{webhook}', 'Api\\WebhookController@checkin')
->middleware('throttle:15,15,checkin_webhook');

View File

@ -39,9 +39,6 @@ Route::middleware('auth')->group(function () {
Route::post('/setting/profile', 'SettingController@updateProfile')->name('setting.profile.update');
Route::get('/setting/privacy', 'SettingController@privacy')->name('setting.privacy');
Route::post('/setting/privacy', 'SettingController@updatePrivacy')->name('setting.privacy.update');
Route::get('/setting/webhooks', 'SettingController@webhooks')->name('setting.webhooks');
Route::post('/setting/webhooks', 'SettingController@storeWebhooks')->name('setting.webhooks.store');
Route::delete('/setting/webhooks/{webhook}', 'SettingController@destroyWebhooks')->name('setting.webhooks.destroy');
Route::get('/setting/import', 'SettingController@import')->name('setting.import');
Route::post('/setting/import', 'SettingController@storeImport')->name('setting.import');
Route::delete('/setting/import', 'SettingController@destroyImport')->name('setting.import.destroy');

View File

@ -1,2 +0,0 @@
*
!.gitignore

View File

@ -1,148 +0,0 @@
<?php
namespace Tests\Feature\Api\Webhook;
use App\CheckinWebhook;
use App\Ejaculation;
use App\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Carbon;
use Tests\TestCase;
class CheckinWebhookTest extends TestCase
{
use RefreshDatabase;
protected function setUp(): void
{
parent::setUp();
$this->seed();
Carbon::setTestNow('2020-07-21 19:19:19');
}
protected function tearDown(): void
{
parent::tearDown();
Carbon::setTestNow();
}
public function testSuccessful()
{
$user = factory(User::class)->create();
$webhook = factory(CheckinWebhook::class)->create(['user_id' => $user->id]);
$response = $this->postJson('/api/webhooks/checkin/' . $webhook->id, [
'checked_in_at' => Carbon::create(2019, 7, 21, 19, 19, 19)->toIso8601String(),
'note' => 'test test test',
'link' => 'http://example.com',
'tags' => ['foo', 'bar'],
'is_private' => false,
'is_too_sensitive' => false,
]);
$response->assertStatus(200)
->assertJsonPath('status', 200);
$checkinId = $response->json('checkin.id');
$ejaculation = Ejaculation::find($checkinId);
$this->assertEquals(Carbon::create(2019, 7, 21, 19, 19, 0), $ejaculation->ejaculated_date);
$this->assertSame('test test test', $ejaculation->note);
$this->assertSame('http://example.com', $ejaculation->link);
$this->assertCount(2, $ejaculation->tags);
$this->assertFalse($ejaculation->is_private);
$this->assertFalse($ejaculation->is_too_sensitive);
$this->assertSame(Ejaculation::SOURCE_WEBHOOK, $ejaculation->source);
$this->assertNotEmpty($ejaculation->checkin_webhook_id);
}
public function testSuccessfulPrivateAndSensitive()
{
$user = factory(User::class)->create();
$webhook = factory(CheckinWebhook::class)->create(['user_id' => $user->id]);
$response = $this->postJson('/api/webhooks/checkin/' . $webhook->id, [
'is_private' => true,
'is_too_sensitive' => true,
]);
$response->assertStatus(200)
->assertJsonPath('status', 200);
$checkinId = $response->json('checkin.id');
$ejaculation = Ejaculation::find($checkinId);
$this->assertTrue($ejaculation->is_private);
$this->assertTrue($ejaculation->is_too_sensitive);
$this->assertSame(Ejaculation::SOURCE_WEBHOOK, $ejaculation->source);
$this->assertNotEmpty($ejaculation->checkin_webhook_id);
}
public function testSuccessfulAllDefault()
{
$user = factory(User::class)->create();
$webhook = factory(CheckinWebhook::class)->create(['user_id' => $user->id]);
$response = $this->postJson('/api/webhooks/checkin/' . $webhook->id);
$response->assertStatus(200)
->assertJsonPath('status', 200);
$checkinId = $response->json('checkin.id');
$ejaculation = Ejaculation::find($checkinId);
$this->assertEquals(Carbon::create(2020, 7, 21, 19, 19, 0), $ejaculation->ejaculated_date);
$this->assertEmpty($ejaculation->note);
$this->assertEmpty($ejaculation->link);
$this->assertEmpty($ejaculation->tags);
$this->assertFalse($ejaculation->is_private);
$this->assertFalse($ejaculation->is_too_sensitive);
$this->assertSame(Ejaculation::SOURCE_WEBHOOK, $ejaculation->source);
$this->assertNotEmpty($ejaculation->checkin_webhook_id);
}
public function testUserDestroyed()
{
$webhook = factory(CheckinWebhook::class)->create(['user_id' => null]);
$response = $this->postJson('/api/webhooks/checkin/' . $webhook->id);
$response->assertStatus(404)
->assertJsonPath('status', 404)
->assertJsonPath('error.message', 'The webhook is unavailable');
}
public function testValidationFailed()
{
$user = factory(User::class)->create();
$webhook = factory(CheckinWebhook::class)->create(['user_id' => $user->id]);
$response = $this->postJson('/api/webhooks/checkin/' . $webhook->id, [
'checked_in_at' => new Carbon('1999-12-31T23:59:00+0900'),
'tags' => [
'Has spaces'
]
]);
$response->assertStatus(422)
->assertJsonPath('status', 422)
->assertJsonPath('error.message', 'Validation failed')
->assertJsonCount(2, 'error.violations');
}
public function testConflictCheckedInAt()
{
$user = factory(User::class)->create();
$webhook = factory(CheckinWebhook::class)->create(['user_id' => $user->id]);
$ejaculatedDate = new Carbon('2020-07-21T19:19:00+0900');
factory(Ejaculation::class)->create([
'user_id' => $user->id,
'ejaculated_date' => $ejaculatedDate
]);
$response = $this->postJson('/api/webhooks/checkin/' . $webhook->id, [
'checked_in_at' => $ejaculatedDate,
]);
$response->assertStatus(422)
->assertJsonPath('status', 422)
->assertJsonPath('error.message', 'Checkin already exists in this time');
}
}

View File

@ -1,75 +0,0 @@
<?php
namespace Tests\Feature\Setting;
use App\CheckinWebhook;
use App\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
class WebhookTest extends TestCase
{
use RefreshDatabase;
protected function setUp(): void
{
parent::setUp();
$this->seed();
}
public function testStoreWebhooks()
{
$user = factory(User::class)->create();
$response = $this->actingAs($user)
->followingRedirects()
->post('/setting/webhooks', ['name' => 'example']);
$response->assertStatus(200)
->assertViewIs('setting.webhooks');
$this->assertDatabaseHas('checkin_webhooks', ['user_id' => $user->id, 'name' => 'example']);
}
public function testStoreWebhooksHas9Hooks()
{
$user = factory(User::class)->create();
$webhooks = factory(CheckinWebhook::class, CheckinWebhook::PER_USER_LIMIT - 1)->create(['user_id' => $user->id]);
$response = $this->actingAs($user)
->followingRedirects()
->post('/setting/webhooks', ['name' => 'example9']);
$response->assertStatus(200)
->assertViewIs('setting.webhooks');
$this->assertDatabaseHas('checkin_webhooks', ['user_id' => $user->id, 'name' => 'example9']);
}
public function testStoreWebhooksHas10Hooks()
{
$user = factory(User::class)->create();
$webhooks = factory(CheckinWebhook::class, CheckinWebhook::PER_USER_LIMIT)->create(['user_id' => $user->id]);
$response = $this->actingAs($user)
->followingRedirects()
->post('/setting/webhooks', ['name' => 'example10']);
$response->assertStatus(200)
->assertViewIs('setting.webhooks');
$this->assertDatabaseMissing('checkin_webhooks', ['user_id' => $user->id, 'name' => 'example10']);
}
public function testDestroyWebhooks()
{
$user = factory(User::class)->create();
$webhook = factory(CheckinWebhook::class)->create(['user_id' => $user->id]);
$response = $this->actingAs($user)
->followingRedirects()
->delete('/setting/webhooks/' . $webhook->id);
$response->assertStatus(200)
->assertViewIs('setting.webhooks')
->assertSee('削除しました');
$this->assertTrue($webhook->refresh()->trashed());
}
}

View File

@ -277,48 +277,6 @@ class CheckinCsvImporterTest extends TestCase
$this->assertEquals(Ejaculation::SOURCE_CSV, $ejaculation->source);
}
public function testIsPrivateUTF8()
{
$user = factory(User::class)->create();
$importer = new CheckinCsvImporter($user, __DIR__ . '/../../fixture/Csv/private.utf8.csv');
$importer->execute();
$ejaculations = $user->ejaculations()->orderBy('ejaculated_date')->get();
$this->assertSame(9, $ejaculations->count());
$this->assertTrue($ejaculations[0]->is_private);
$this->assertTrue($ejaculations[1]->is_private);
$this->assertTrue($ejaculations[2]->is_private);
$this->assertTrue($ejaculations[3]->is_private);
$this->assertFalse($ejaculations[4]->is_private);
$this->assertFalse($ejaculations[5]->is_private);
$this->assertFalse($ejaculations[6]->is_private);
$this->assertFalse($ejaculations[7]->is_private);
$this->assertFalse($ejaculations[8]->is_private);
}
public function testIsTooSensitiveUTF8()
{
$user = factory(User::class)->create();
$importer = new CheckinCsvImporter($user, __DIR__ . '/../../fixture/Csv/too-sensitive.utf8.csv');
$importer->execute();
$ejaculations = $user->ejaculations()->orderBy('ejaculated_date')->get();
$this->assertSame(9, $ejaculations->count());
$this->assertTrue($ejaculations[0]->is_too_sensitive);
$this->assertTrue($ejaculations[1]->is_too_sensitive);
$this->assertTrue($ejaculations[2]->is_too_sensitive);
$this->assertTrue($ejaculations[3]->is_too_sensitive);
$this->assertFalse($ejaculations[4]->is_too_sensitive);
$this->assertFalse($ejaculations[5]->is_too_sensitive);
$this->assertFalse($ejaculations[6]->is_too_sensitive);
$this->assertFalse($ejaculations[7]->is_too_sensitive);
$this->assertFalse($ejaculations[8]->is_too_sensitive);
}
public function testDontThrowUniqueKeyViolation()
{
$user = factory(User::class)->create();

View File

@ -1,185 +0,0 @@
<?php
namespace Tests\Unit\Services;
use App\ContentProvider;
use App\MetadataResolver\MetadataResolver;
use App\MetadataResolver\ResolverCircuitBreakException;
use App\MetadataResolver\UncaughtResolverException;
use App\Services\MetadataResolveService;
use Carbon\Carbon;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\ClientException;
use GuzzleHttp\Exception\ServerException;
use GuzzleHttp\Handler\MockHandler;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Psr7\Response;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Mockery\MockInterface;
use Tests\TestCase;
class MetadataResolverServiceTest extends TestCase
{
use RefreshDatabase;
protected function setUp(): void
{
parent::setUp();
$this->seed();
Carbon::setTestNow('2020-07-21 19:19:19');
// FIXME: 今書かれてるテストはresolveのHTTPリクエストのみを考慮しているので、ContentProviderにデータがないとリクエスト回数がずれる
factory(ContentProvider::class)->create();
}
protected function tearDown(): void
{
parent::tearDown();
Carbon::setTestNow();
}
public function testOnRuntimeException()
{
$this->mock(MetadataResolver::class, function (MockInterface $mock) {
$mock->shouldReceive('resolve')->andReturnUsing(function ($url) {
throw new \RuntimeException('Something happened!');
});
});
try {
$service = app()->make(MetadataResolveService::class);
$service->execute('http://example.com');
} catch (UncaughtResolverException $e) {
$this->assertDatabaseHas('metadata', [
'url' => 'http://example.com',
'error_at' => new Carbon('2020-07-21 19:19:19'),
'error_count' => 1,
'error_exception_class' => \RuntimeException::class,
'error_http_code' => null,
'error_body' => 'Something happened!',
]);
return;
}
$this->fail();
}
public function testOnHttpClientError()
{
$handler = HandlerStack::create(new MockHandler([new Response(404)]));
$client = new Client(['handler' => $handler]);
$this->instance(Client::class, $client);
try {
$service = app()->make(MetadataResolveService::class);
$service->execute('http://example.com');
} catch (UncaughtResolverException $e) {
$this->assertDatabaseHas('metadata', [
'url' => 'http://example.com',
'error_at' => new Carbon('2020-07-21 19:19:19'),
'error_count' => 1,
'error_exception_class' => ClientException::class,
'error_http_code' => 404,
]);
return;
}
$this->fail();
}
public function testOnHttpServerError()
{
$handler = HandlerStack::create(new MockHandler([new Response(503), new Response(503)]));
$client = new Client(['handler' => $handler]);
$this->instance(Client::class, $client);
try {
$service = app()->make(MetadataResolveService::class);
$service->execute('http://example.com');
} catch (UncaughtResolverException $e) {
$this->assertDatabaseHas('metadata', [
'url' => 'http://example.com',
'error_at' => new Carbon('2020-07-21 19:19:19'),
'error_count' => 1,
'error_exception_class' => ServerException::class,
'error_http_code' => 503,
]);
return;
}
$this->fail();
}
public function testCircuitBreak()
{
$this->mock(MetadataResolver::class, function (MockInterface $mock) {
$mock->shouldReceive('resolve')->andReturnUsing(function ($url) {
throw new \RuntimeException('Something happened!');
});
});
try {
for ($i = 0; $i < 6; $i++) {
try {
$service = app()->make(MetadataResolveService::class);
$service->execute('http://example.com');
} catch (UncaughtResolverException $e) {
}
}
} catch (ResolverCircuitBreakException $e) {
$this->assertDatabaseHas('metadata', [
'url' => 'http://example.com',
'error_at' => new Carbon('2020-07-21 19:19:19'),
'error_count' => 5,
'error_exception_class' => \RuntimeException::class,
'error_http_code' => null,
'error_body' => 'Something happened!',
]);
return;
}
$this->fail();
}
public function testOnResurrect()
{
$successBody = <<<HTML
<!doctype html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="og:title" content="OGP Title">
<meta name="og:description" content="OGP Description">
<title>Test Document</title>
</head>
<body>
</body>
</html>
HTML;
$handler = HandlerStack::create(new MockHandler([
new Response(404),
new Response(200, ['Content-Type' => 'text/html'], $successBody),
]));
$client = new Client(['handler' => $handler]);
$this->instance(Client::class, $client);
for ($i = 0; $i < 2; $i++) {
try {
$service = app()->make(MetadataResolveService::class);
$service->execute('http://example.com');
} catch (UncaughtResolverException $e) {
}
}
$this->assertDatabaseHas('metadata', [
'url' => 'http://example.com',
'title' => 'OGP Title',
'description' => 'OGP Description',
'image' => '',
'error_at' => null,
'error_count' => 0,
'error_exception_class' => null,
'error_http_code' => null,
'error_body' => null,
]);
}
}

View File

@ -1,10 +0,0 @@
日時,非公開
2020/01/23 06:01:00,true
2020/01/23 06:02:00,TRUE
2020/01/23 06:03:00,True
2020/01/23 06:04:00,1
2020/01/23 07:01:00,false
2020/01/23 07:02:00,FALSE
2020/01/23 07:03:00,False
2020/01/23 07:04:00,0
2020/01/23 07:05:00,
1 日時 非公開
2 2020/01/23 06:01:00 true
3 2020/01/23 06:02:00 TRUE
4 2020/01/23 06:03:00 True
5 2020/01/23 06:04:00 1
6 2020/01/23 07:01:00 false
7 2020/01/23 07:02:00 FALSE
8 2020/01/23 07:03:00 False
9 2020/01/23 07:04:00 0
10 2020/01/23 07:05:00

View File

@ -1,10 +0,0 @@
日時,センシティブ
2020/01/23 06:01:00,true
2020/01/23 06:02:00,TRUE
2020/01/23 06:03:00,True
2020/01/23 06:04:00,1
2020/01/23 07:01:00,false
2020/01/23 07:02:00,FALSE
2020/01/23 07:03:00,False
2020/01/23 07:04:00,0
2020/01/23 07:05:00,
1 日時 センシティブ
2 2020/01/23 06:01:00 true
3 2020/01/23 06:02:00 TRUE
4 2020/01/23 06:03:00 True
5 2020/01/23 06:04:00 1
6 2020/01/23 07:01:00 false
7 2020/01/23 07:02:00 FALSE
8 2020/01/23 07:03:00 False
9 2020/01/23 07:04:00 0
10 2020/01/23 07:05:00

View File

@ -5,11 +5,9 @@
"module": "es2015",
"moduleResolution": "node",
"strict": true,
"experimentalDecorators": true,
"jsx": "react",
"esModuleInterop": true
"experimentalDecorators": true
},
"include": [
"resources/assets/js/**/*"
]
}
}

3
webpack.mix.js vendored
View File

@ -20,8 +20,7 @@ mix.ts('resources/assets/js/app.ts', 'public/js')
.ts('resources/assets/js/setting/privacy.ts', 'public/js/setting')
.ts('resources/assets/js/setting/import.ts', 'public/js/setting')
.ts('resources/assets/js/setting/deactivate.ts', 'public/js/setting')
.ts('resources/assets/js/setting/webhooks.ts', 'public/js/setting')
.ts('resources/assets/js/checkin.tsx', 'public/js')
.ts('resources/assets/js/checkin.ts', 'public/js')
.sass('resources/assets/sass/app.scss', 'public/css')
.autoload({
jquery: ['$', 'jQuery', 'window.jQuery'],

2365
yarn.lock

File diff suppressed because it is too large Load Diff