Merge pull request #360 from shikorism/develop

Release 20200524.2130
This commit is contained in:
shibafu 2020-05-24 21:34:02 +09:00 committed by GitHub
commit 8021d42a62
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
116 changed files with 3923 additions and 1378 deletions

View File

@ -2,9 +2,10 @@ APP_NAME=Tissue
APP_ENV=local
APP_KEY=
APP_DEBUG=true
APP_LOG_LEVEL=debug
APP_URL=http://localhost
LOG_CHANNEL=stack
# テストにモックを使用するか falseの場合は実際のHTML等を取得してテストする
TEST_USE_HTTP_MOCK=true
@ -33,12 +34,20 @@ MAIL_ENCRYPTION=tls
MAIL_FROM_ADDRESS=support@mail.shikorism.net
MAIL_FROM_NAME=Tissue
AWS_ACCESS_KEY_ID=
AWS_SECRET_ACCESS_KEY=
AWS_DEFAULT_REGION=us-east-1
AWS_BUCKET=
SPARKPOST_SECRET=
PUSHER_APP_ID=
PUSHER_APP_KEY=
PUSHER_APP_SECRET=
MIX_PUSHER_APP_KEY="${PUSHER_APP_KEY}"
MIX_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}"
# (Optional) reCAPTCHA Key
# https://www.google.com/recaptcha
NOCAPTCHA_SECRET=

2
.gitignore vendored
View File

@ -15,6 +15,8 @@ Homestead.yaml
npm-debug.log
yarn-error.log
.env
.env.backup
.phpunit.result.cache
*.iml
.php_cs
.php_cs.cache

View File

@ -7,8 +7,8 @@ a.k.a. shikorism.net
## 構成
- Laravel 5.5
- Bootstrap 4.3.1
- Laravel 6
- Bootstrap 4.4.1
## 実行環境

View File

@ -12,9 +12,12 @@ class Ejaculation extends Model
{
use HasEagerLimit;
const SOURCE_WEB = 'web';
const SOURCE_CSV = 'csv';
protected $fillable = [
'user_id', 'ejaculated_date',
'note', 'geo_latitude', 'geo_longitude', 'link',
'note', 'geo_latitude', 'geo_longitude', 'link', 'source',
'is_private', 'is_too_sensitive'
];
@ -44,6 +47,11 @@ class Ejaculation extends Model
return $this->hasMany(Like::class);
}
public function scopeOnlyWebCheckin(Builder $query)
{
return $query->where('ejaculations.source', Ejaculation::SOURCE_WEB);
}
public function scopeWithLikes(Builder $query)
{
if (Auth::check()) {

View File

@ -0,0 +1,30 @@
<?php
namespace App\Exceptions;
use Illuminate\Support\Arr;
use Throwable;
class CsvImportException extends \RuntimeException
{
/** @var string[] */
private $errors;
/**
* CsvImportException constructor.
* @param string[] $errors
*/
public function __construct(...$errors)
{
parent::__construct(Arr::first($errors));
$this->errors = $errors;
}
/**
* @return string[]
*/
public function getErrors(): array
{
return $this->errors;
}
}

View File

@ -25,10 +25,10 @@ class Handler extends ExceptionHandler
/**
* Report or log an exception.
*
* This is a great spot to send exceptions to Sentry, Bugsnag, etc.
*
* @param \Exception $exception
* @return void
*
* @throws \Exception
*/
public function report(Exception $exception)
{
@ -40,7 +40,9 @@ class Handler extends ExceptionHandler
*
* @param \Illuminate\Http\Request $request
* @param \Exception $exception
* @return \Illuminate\Http\Response
* @return \Symfony\Component\HttpFoundation\Response
*
* @throws \Exception
*/
public function render($request, Exception $exception)
{

View File

@ -5,6 +5,7 @@ namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\User;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
class RegisterController extends Controller
@ -50,7 +51,7 @@ class RegisterController extends Controller
$rules = [
'name' => 'required|string|regex:/^[a-zA-Z0-9_-]+$/u|max:15|unique:users|unique:deactivated_users',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:6|confirmed'
'password' => 'required|string|min:8|confirmed'
];
// reCAPTCHAのキーが設定されている場合、判定を有効化
@ -78,7 +79,7 @@ class RegisterController extends Controller
'name' => $data['name'],
'display_name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
'password' => Hash::make($data['password']),
'is_protected' => $data['is_protected'] ?? false,
'accept_analytics' => $data['accept_analytics'] ?? false
]);

View File

@ -0,0 +1,41 @@
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\VerifiesEmails;
class VerificationController extends Controller
{
/*
|--------------------------------------------------------------------------
| Email Verification Controller
|--------------------------------------------------------------------------
|
| This controller is responsible for handling email verification for any
| user that recently registered with the application. Emails may also
| be re-sent if the user didn't receive the original email message.
|
*/
use VerifiesEmails;
/**
* Where to redirect users after verification.
*
* @var string
*/
protected $redirectTo = '/home';
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('auth');
$this->middleware('signed')->only('verify');
$this->middleware('throttle:6,1')->only('verify', 'resend');
}
}

View File

@ -57,6 +57,7 @@ class EjaculationController extends Controller
'ejaculated_date' => Carbon::createFromFormat('Y/m/d H:i', $inputs['date'] . ' ' . $inputs['time']),
'note' => $inputs['note'] ?? '',
'link' => $inputs['link'] ?? '',
'source' => Ejaculation::SOURCE_WEB,
'is_private' => $request->has('is_private') ?? false,
'is_too_sensitive' => $request->has('is_too_sensitive') ?? false
]);
@ -184,4 +185,9 @@ class EjaculationController extends Controller
return redirect()->route('user.profile', ['name' => $user->name])->with('status', '削除しました。');
}
public function tools()
{
return view('ejaculation.tools');
}
}

View File

@ -66,10 +66,12 @@ SQL
->where('users.is_protected', false)
->where('ejaculations.is_private', false)
->where('ejaculations.link', '<>', '')
->where('ejaculations.ejaculated_date', '<=', Carbon::now())
->orderBy('ejaculations.ejaculated_date', 'desc')
->select('ejaculations.*')
->with('user', 'tags')
->withLikes()
->onlyWebCheckin()
->take(21)
->get();

View File

@ -3,6 +3,10 @@
namespace App\Http\Controllers;
use App\DeactivatedUser;
use App\Ejaculation;
use App\Exceptions\CsvImportException;
use App\Services\CheckinCsvExporter;
use App\Services\CheckinCsvImporter;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
@ -71,6 +75,79 @@ class SettingController extends Controller
return redirect()->route('setting.privacy')->with('status', 'プライバシー設定を更新しました。');
}
public function import()
{
return view('setting.import');
}
public function storeImport(Request $request)
{
$validated = $request->validate([
'file' => 'required|file'
], [], [
'file' => 'ファイル'
]);
$file = $request->file('file');
if (!$file->isValid()) {
return redirect()->route('setting.import')->withErrors(['file' => 'ファイルのアップロードに失敗しました。']);
}
try {
set_time_limit(0);
$importer = new CheckinCsvImporter(Auth::user(), $file->path());
$imported = $importer->execute();
return redirect()->route('setting.import')->with('status', "{$imported}件のインポートに性交しました。");
} catch (CsvImportException $e) {
return redirect()->route('setting.import')->with('import_errors', $e->getErrors());
}
}
public function destroyImport()
{
Auth::user()
->ejaculations()
->where('ejaculations.source', Ejaculation::SOURCE_CSV)
->delete();
return redirect()->route('setting.import')->with('status', '削除が完了しました。');
}
public function export()
{
return view('setting.export');
}
public function exportToCsv(Request $request)
{
$validated = $request->validate([
'charset' => ['required', Rule::in(['utf8', 'sjis'])]
]);
$charsets = [
'utf8' => 'UTF-8',
'sjis' => 'SJIS-win'
];
$filename = tempnam(sys_get_temp_dir(), 'tissue_export_tmp_');
try {
// 気休め
set_time_limit(0);
$exporter = new CheckinCsvExporter(Auth::user(), $filename, $charsets[$validated['charset']]);
$exporter->execute();
} catch (\Throwable $e) {
unlink($filename);
throw $e;
}
return response()
->download($filename, 'TissueCheckin_' . date('Y-m-d_H-i-s') . '.csv')
->deleteFileAfterSend(true);
}
public function deactivate()
{
return view('setting.deactivate');

View File

@ -4,6 +4,7 @@ namespace App\Http\Controllers;
use App\Ejaculation;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
class TimelineController extends Controller
{
@ -13,10 +14,12 @@ class TimelineController extends Controller
->where('users.is_protected', false)
->where('ejaculations.is_private', false)
->where('ejaculations.link', '<>', '')
->where('ejaculations.ejaculated_date', '<=', Carbon::now())
->orderBy('ejaculations.ejaculated_date', 'desc')
->select('ejaculations.*')
->with('user', 'tags')
->withLikes()
->onlyWebCheckin()
->paginate(21);
return view('timeline.public')->with(compact('ejaculations'));

View File

@ -5,9 +5,11 @@ namespace App\Http\Controllers;
use App\Ejaculation;
use App\User;
use Carbon\Carbon;
use Carbon\CarbonInterface;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Validator;
class UserController extends Controller
{
@ -32,6 +34,7 @@ note,
is_private,
is_too_sensitive,
link,
source,
to_char(lead(ejaculated_date, 1, NULL) OVER (ORDER BY ejaculated_date DESC), 'YYYY/MM/DD HH24:MI') AS before_date,
to_char(ejaculated_date - (lead(ejaculated_date, 1, NULL) OVER (ORDER BY ejaculated_date DESC)), 'FMDDD日 FMHH24時間 FMMI分') AS ejaculated_span
SQL
@ -59,7 +62,18 @@ SQL
->limit(10)
->get();
return view('user.profile')->with(compact('user', 'ejaculations', 'tags'));
// シコ草
$countByDayQuery = $this->countEjaculationByDay($user)
->where('ejaculated_date', '>=', now()->startOfMonth()->subMonths(9))
->where('ejaculated_date', '<', now()->addMonth()->startOfMonth())
->get();
$countByDay = [];
foreach ($countByDayQuery as $data) {
$date = Carbon::createFromFormat('Y/m/d', $data->date);
$countByDay[$date->timestamp] = $data->count;
}
return view('user.profile')->with(compact('user', 'ejaculations', 'tags', 'countByDay'));
}
public function stats($name)
@ -69,73 +83,72 @@ SQL
abort(404);
}
$dateUntil = now()->addMonth()->startOfMonth();
$availableMonths = $this->makeStatsAvailableMonths($user);
$graphData = $this->makeGraphData($user);
$groupByDay = Ejaculation::select(DB::raw(
<<<'SQL'
to_char(ejaculated_date, 'YYYY/MM/DD') AS "date",
count(*) AS "count"
SQL
))
->where('user_id', $user->id)
->where('ejaculated_date', '<', $dateUntil)
->groupBy(DB::raw("to_char(ejaculated_date, 'YYYY/MM/DD')"))
->orderBy(DB::raw("to_char(ejaculated_date, 'YYYY/MM/DD')"))
->get();
return view('user.stats.index')->with(compact('user', 'graphData', 'availableMonths'));
}
$groupByHour = Ejaculation::select(DB::raw(
<<<'SQL'
to_char(ejaculated_date, 'HH24') AS "hour",
count(*) AS "count"
SQL
))
->where('user_id', $user->id)
->where('ejaculated_date', '<', $dateUntil)
->groupBy(DB::raw("to_char(ejaculated_date, 'HH24')"))
->orderBy(DB::raw('1'))
->get();
$dailySum = [];
$monthlySum = [];
$yearlySum = [];
$dowSum = array_fill(0, 7, 0);
$hourlySum = array_fill(0, 24, 0);
// 年間グラフ用の配列初期化
if ($groupByDay->first() !== null) {
$year = Carbon::createFromFormat('Y/m/d', $groupByDay->first()->date)->year;
$currentYear = date('Y');
for (; $year <= $currentYear; $year++) {
$yearlySum[$year] = 0;
}
public function statsYearly($name, $year)
{
$user = User::where('name', $name)->first();
if (empty($user)) {
abort(404);
}
foreach ($groupByDay as $data) {
$date = Carbon::createFromFormat('Y/m/d', $data->date);
$yearAndMonth = $date->format('Y/m');
$dailySum[$date->timestamp] = $data->count;
$yearlySum[$date->year] += $data->count;
$dowSum[$date->dayOfWeek] += $data->count;
$monthlySum[$yearAndMonth] = ($monthlySum[$yearAndMonth] ?? 0) + $data->count;
$validator = Validator::make(compact('year'), [
'year' => 'required|date_format:Y'
]);
if ($validator->fails()) {
return redirect()->route('user.stats', compact('name'));
}
foreach ($groupByHour as $data) {
$hour = (int)$data->hour;
$hourlySum[$hour] += $data->count;
$availableMonths = $this->makeStatsAvailableMonths($user);
if (!isset($availableMonths[$year])) {
return redirect()->route('user.stats', compact('name'));
}
$graphData = [
'dailySum' => $dailySum,
'dowSum' => $dowSum,
'monthlySum' => $monthlySum,
'yearlyKey' => array_keys($yearlySum),
'yearlySum' => array_values($yearlySum),
'hourlyKey' => array_keys($hourlySum),
'hourlySum' => array_values($hourlySum),
];
$graphData = $this->makeGraphData(
$user,
Carbon::createFromDate($year, 1, 1, config('app.timezone'))->startOfDay(),
Carbon::createFromDate($year, 1, 1, config('app.timezone'))->addYear()->startOfDay()
);
return view('user.stats')->with(compact('user', 'graphData'));
return view('user.stats.yearly')
->with(compact('user', 'graphData', 'availableMonths'))
->with('currentYear', (int) $year);
}
public function statsMonthly($name, $year, $month)
{
$user = User::where('name', $name)->first();
if (empty($user)) {
abort(404);
}
$validator = Validator::make(compact('year', 'month'), [
'year' => 'required|date_format:Y',
'month' => 'required|date_format:m'
]);
if ($validator->fails()) {
return redirect()->route('user.stats.yearly', compact('name', 'year'));
}
$availableMonths = $this->makeStatsAvailableMonths($user);
if (!isset($availableMonths[$year]) || !in_array($month, $availableMonths[$year], false)) {
return redirect()->route('user.stats.yearly', compact('name', 'year'));
}
$graphData = $this->makeGraphData(
$user,
Carbon::createFromDate($year, $month, 1, config('app.timezone'))->startOfDay(),
Carbon::createFromDate($year, $month, 1, config('app.timezone'))->addMonth()->startOfDay()
);
return view('user.stats.monthly')
->with(compact('user', 'graphData', 'availableMonths'))
->with('currentYear', (int) $year)
->with('currentMonth', (int) $month);
}
public function okazu($name)
@ -154,6 +167,7 @@ note,
is_private,
is_too_sensitive,
link,
source,
to_char(lead(ejaculated_date, 1, NULL) OVER (ORDER BY ejaculated_date DESC), 'YYYY/MM/DD HH24:MI') AS before_date,
to_char(ejaculated_date - (lead(ejaculated_date, 1, NULL) OVER (ORDER BY ejaculated_date DESC)), 'FMDDD日 FMHH24時間 FMMI分') AS ejaculated_span
SQL
@ -189,4 +203,104 @@ SQL
return view('user.likes')->with(compact('user', 'likes'));
}
private function makeStatsAvailableMonths(User $user): array
{
$availableMonths = [];
$oldest = $user->ejaculations()->orderBy('ejaculated_date')->first();
if (isset($oldest)) {
$oldestMonth = $oldest->ejaculated_date->startOfMonth();
$currentMonth = now()->startOfMonth();
for ($month = $currentMonth; $oldestMonth <= $currentMonth; $month = $month->subMonth()) {
if (!isset($availableMonths[$month->year])) {
$availableMonths[$month->year] = [];
}
$availableMonths[$month->year][] = $month->month;
}
}
return $availableMonths;
}
private function makeGraphData(User $user, CarbonInterface $dateSince = null, CarbonInterface $dateUntil = null): array
{
if ($dateUntil === null) {
$dateUntil = now()->addMonth()->startOfMonth();
}
$dateCondition = [
['ejaculated_date', '<', $dateUntil],
];
if ($dateSince !== null) {
$dateCondition[] = ['ejaculated_date', '>=', $dateSince];
}
$groupByDay = $this->countEjaculationByDay($user)
->where($dateCondition)
->get();
$groupByHour = Ejaculation::select(DB::raw(
<<<'SQL'
to_char(ejaculated_date, 'HH24') AS "hour",
count(*) AS "count"
SQL
))
->where('user_id', $user->id)
->where($dateCondition)
->groupBy(DB::raw("to_char(ejaculated_date, 'HH24')"))
->orderBy(DB::raw('1'))
->get();
$dailySum = [];
$monthlySum = [];
$yearlySum = [];
$dowSum = array_fill(0, 7, 0);
$hourlySum = array_fill(0, 24, 0);
// 年間グラフ用の配列初期化
if ($groupByDay->first() !== null) {
$year = Carbon::createFromFormat('Y/m/d', $groupByDay->first()->date)->year;
$currentYear = date('Y');
for (; $year <= $currentYear; $year++) {
$yearlySum[$year] = 0;
}
}
foreach ($groupByDay as $data) {
$date = Carbon::createFromFormat('Y/m/d', $data->date);
$yearAndMonth = $date->format('Y/m');
$dailySum[$date->timestamp] = $data->count;
$yearlySum[$date->year] += $data->count;
$dowSum[$date->dayOfWeek] += $data->count;
$monthlySum[$yearAndMonth] = ($monthlySum[$yearAndMonth] ?? 0) + $data->count;
}
foreach ($groupByHour as $data) {
$hour = (int)$data->hour;
$hourlySum[$hour] += $data->count;
}
return [
'dailySum' => $dailySum,
'dowSum' => $dowSum,
'monthlySum' => $monthlySum,
'yearlyKey' => array_keys($yearlySum),
'yearlySum' => array_values($yearlySum),
'hourlyKey' => array_keys($hourlySum),
'hourlySum' => array_values($hourlySum),
];
}
private function countEjaculationByDay(User $user)
{
return Ejaculation::select(DB::raw(
<<<'SQL'
to_char(ejaculated_date, 'YYYY/MM/DD') AS "date",
count(*) AS "count"
SQL
))
->where('user_id', $user->id)
->groupBy(DB::raw("to_char(ejaculated_date, 'YYYY/MM/DD')"))
->orderBy(DB::raw("to_char(ejaculated_date, 'YYYY/MM/DD')"));
}
}

View File

@ -14,11 +14,11 @@ class Kernel extends HttpKernel
* @var array
*/
protected $middleware = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
\App\Http\Middleware\TrustProxies::class,
\App\Http\Middleware\CheckForMaintenanceMode::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\App\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
\App\Http\Middleware\TrustProxies::class,
];
/**
@ -45,7 +45,7 @@ class Kernel extends HttpKernel
\Illuminate\Session\Middleware\StartSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
'throttle:60,1',
'bindings',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
];
@ -57,11 +57,32 @@ class Kernel extends HttpKernel
* @var array
*/
protected $routeMiddleware = [
'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
];
/**
* The priority-sorted list of middleware.
*
* This forces non-global middleware to always be in the given order.
*
* @var array
*/
protected $middlewarePriority = [
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\Authenticate::class,
\Illuminate\Routing\Middleware\ThrottleRequests::class,
\Illuminate\Session\Middleware\AuthenticateSession::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
\Illuminate\Auth\Middleware\Authorize::class,
];
}

View File

@ -0,0 +1,21 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Auth\Middleware\Authenticate as Middleware;
class Authenticate extends Middleware
{
/**
* Get the path the user should be redirected to when they are not authenticated.
*
* @param \Illuminate\Http\Request $request
* @return string|null
*/
protected function redirectTo($request)
{
if (! $request->expectsJson()) {
return route('login');
}
}
}

View File

@ -0,0 +1,17 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode as Middleware;
class CheckForMaintenanceMode extends Middleware
{
/**
* The URIs that should be reachable while maintenance mode is enabled.
*
* @var array
*/
protected $except = [
//
];
}

View File

@ -10,20 +10,14 @@ class TrustProxies extends Middleware
/**
* The trusted proxies for this application.
*
* @var array
* @var array|string
*/
protected $proxies = '**';
/**
* The current proxy header mappings.
* The headers that should be used to detect proxies.
*
* @var array
* @var int
*/
protected $headers = [
Request::HEADER_FORWARDED => 'FORWARDED',
Request::HEADER_X_FORWARDED_FOR => 'X_FORWARDED_FOR',
Request::HEADER_X_FORWARDED_HOST => 'X_FORWARDED_HOST',
Request::HEADER_X_FORWARDED_PORT => 'X_FORWARDED_PORT',
Request::HEADER_X_FORWARDED_PROTO => 'X_FORWARDED_PROTO',
];
protected $headers = Request::HEADER_X_FORWARDED_ALL;
}

View File

@ -6,6 +6,13 @@ use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as BaseVerifier;
class VerifyCsrfToken extends BaseVerifier
{
/**
* Indicates whether the XSRF-TOKEN cookie should be set on the response.
*
* @var bool
*/
protected $addHttpCookie = true;
/**
* The URIs that should be excluded from CSRF verification.
*

View File

@ -3,6 +3,7 @@
namespace App\MetadataResolver;
use GuzzleHttp\Client;
use Illuminate\Support\Str;
use Symfony\Component\DomCrawler\Crawler;
class NijieResolver implements Resolver
@ -50,8 +51,8 @@ class NijieResolver implements Resolver
$metadata->description = '投稿者: ' . $data['author']['name'] . PHP_EOL . $data['description'];
if (
isset($data['thumbnailUrl']) &&
!ends_with($data['thumbnailUrl'], '.gif') &&
!ends_with($data['thumbnailUrl'], '.mp4')
!Str::endsWith($data['thumbnailUrl'], '.gif') &&
!Str::endsWith($data['thumbnailUrl'], '.mp4')
) {
// サムネイルからメイン画像に
$metadata->image = str_replace('__rs_l160x160/', '', $data['thumbnailUrl']);

View File

@ -19,6 +19,8 @@ class AppServiceProvider extends ServiceProvider
Blade::directive('parsedown', function ($expression) {
return "<?php echo app('parsedown')->text($expression); ?>";
});
stream_filter_register('convert.mbstring.*', 'Stream_Filter_Mbstring');
}
/**

View File

@ -2,6 +2,8 @@
namespace App\Providers;
use Illuminate\Auth\Events\Registered;
use Illuminate\Auth\Listeners\SendEmailVerificationNotification;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Event;
@ -13,6 +15,9 @@ class EventServiceProvider extends ServiceProvider
* @var array
*/
protected $listen = [
Registered::class => [
SendEmailVerificationNotification::class,
],
'App\Events\LinkDiscovered' => [
'App\Listeners\LinkCollector'
]

82
app/Rules/CsvDateTime.php Normal file
View File

@ -0,0 +1,82 @@
<?php
namespace App\Rules;
use Illuminate\Contracts\Validation\Rule;
/**
* CSVインポート機能の日時バリデーションルール
* @package App\Rules
*/
class CsvDateTime implements Rule
{
const VALID_FORMATS = [
'Y/m/d H:i:s',
'Y/n/j G:i:s',
'Y/m/d H:i',
'Y/n/j G:i',
];
const MINIMUM_TIMESTAMP = 946652400; // 2000-01-01 00:00:00 JST
const MAXIMUM_TIMESTAMP = 4102412399; // 2099-12-31 23:59:59 JST
/** @var string Validation error message */
private $message = ':attributeの形式は "年/月/日 時:分" にしてください。';
/**
* 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)
{
// この辺の実装の元ネタは、LaravelのValidatesAttributes#validateDateFormat()
if (!is_string($value)) {
return false;
}
foreach (self::VALID_FORMATS as $format) {
$date = \DateTime::createFromFormat('!' . $format, $value);
if (!$date) {
continue;
}
$timestamp = (int) $date->format('U');
if ($timestamp < self::MINIMUM_TIMESTAMP || self::MAXIMUM_TIMESTAMP < $timestamp) {
$this->message = ':attributeは 2000/01/01 00:00 〜 2099/12/31 23:59 の間のみ対応しています。';
return false;
}
$formatted = $date->format($format);
if ($formatted === $value) {
return true;
}
}
return false;
}
/**
* Get the validation error message.
*
* @return string
*/
public function message()
{
return $this->message;
}
}

View File

@ -0,0 +1,57 @@
<?php
namespace App\Services;
use App\User;
use Illuminate\Support\Facades\DB;
use League\Csv\Writer;
class CheckinCsvExporter
{
/** @var User Target user */
private $user;
/** @var string Output filename */
private $filename;
/** @var string Output charset */
private $charset;
public function __construct(User $user, string $filename, string $charset)
{
$this->user = $user;
$this->filename = $filename;
$this->charset = $charset;
}
public function execute()
{
$csv = Writer::createFromPath($this->filename, 'wb');
$csv->setNewline("\r\n");
if ($this->charset === 'SJIS-win') {
$csv->addStreamFilter('convert.mbstring.encoding.UTF-8:SJIS-win');
}
$header = ['日時', 'ノート', 'オカズリンク'];
for ($i = 1; $i <= 32; $i++) {
$header[] = "タグ{$i}";
}
$csv->insertOne($header);
DB::transaction(function () use ($csv) {
// TODO: そんなに読み取り整合性を保つ努力はしていないのと、chunkの件数これでいいか分からない
$this->user->ejaculations()->with('tags')->orderBy('ejaculated_date')
->chunk(1000, function ($ejaculations) use ($csv) {
foreach ($ejaculations as $ejaculation) {
$record = [
$ejaculation->ejaculated_date->format('Y/m/d H:i'),
$ejaculation->note,
$ejaculation->link,
];
foreach ($ejaculation->tags->take(32) as $tag) {
$record[] = $tag->name;
}
$csv->insertOne($record);
}
});
});
}
}

View File

@ -0,0 +1,212 @@
<?php
declare(strict_types=1);
namespace App\Services;
use App\Ejaculation;
use App\Exceptions\CsvImportException;
use App\Rules\CsvDateTime;
use App\Tag;
use App\User;
use Carbon\Carbon;
use Illuminate\Database\QueryException;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use League\Csv\Reader;
use Throwable;
class CheckinCsvImporter
{
/** @var int 取り込み件数の上限 */
private const IMPORT_LIMIT = 5000;
/** @var User Target user */
private $user;
/** @var string CSV filename */
private $filename;
public function __construct(User $user, string $filename)
{
$this->user = $user;
$this->filename = $filename;
}
/**
* インポート処理を実行します。
* @return int 取り込んだ件数
*/
public function execute(): int
{
// Guess charset
$charset = $this->guessCharset($this->filename);
// Open CSV
$csv = Reader::createFromPath($this->filename, 'r');
$csv->setHeaderOffset(0);
if ($charset === 'SJIS-win') {
$csv->addStreamFilter('convert.mbstring.encoding.SJIS-win:UTF-8');
}
// Import
return DB::transaction(function () use ($csv) {
$alreadyImportedCount = $this->user->ejaculations()->where('ejaculations.source', Ejaculation::SOURCE_CSV)->count();
$errors = [];
if (!in_array('日時', $csv->getHeader(), true)) {
$errors[] = '日時列は必須です。';
}
if (!empty($errors)) {
throw new CsvImportException(...$errors);
}
$imported = 0;
foreach ($csv->getRecords() as $offset => $record) {
$line = $offset + 1;
if (self::IMPORT_LIMIT <= $alreadyImportedCount + $imported) {
$limit = self::IMPORT_LIMIT;
$errors[] = "{$line} 行 : インポート機能で取り込めるデータは{$limit}件までに制限されています。これ以上取り込みできません。";
throw new CsvImportException(...$errors);
}
$ejaculation = new Ejaculation(['user_id' => $this->user->id]);
$validator = Validator::make($record, [
'日時' => ['required', new CsvDateTime()],
'ノート' => 'nullable|string|max:500',
'オカズリンク' => 'nullable|url|max:2000',
]);
if ($validator->fails()) {
foreach ($validator->errors()->all() as $message) {
$errors[] = "{$line} 行 : {$message}";
}
continue;
}
$ejaculation->ejaculated_date = Carbon::createFromFormat('!Y/m/d H:i+', $record['日時']);
$ejaculation->note = str_replace(["\r\n", "\r"], "\n", $record['ノート'] ?? '');
$ejaculation->link = $record['オカズリンク'] ?? '';
$ejaculation->source = Ejaculation::SOURCE_CSV;
try {
$tags = $this->parseTags($line, $record);
} catch (CsvImportException $e) {
$errors = array_merge($errors, $e->getErrors());
continue;
}
DB::beginTransaction();
try {
$ejaculation->save();
if (!empty($tags)) {
$ejaculation->tags()->sync(collect($tags)->pluck('id'));
}
DB::commit();
$imported++;
} catch (QueryException $e) {
DB::rollBack();
if ($e->errorInfo[0] === '23505') {
$errors[] = "{$line} 行 : すでにこの日時のチェックインデータが存在します。";
continue;
}
throw $e;
} catch (Throwable $e) {
DB::rollBack();
throw $e;
}
}
if (!empty($errors)) {
throw new CsvImportException(...$errors);
}
return $imported;
});
}
/**
* 指定されたファイルを読み込み、文字コードの判定を行います。
* @param string $filename CSVファイル名
* @param int $samplingLength ファイルの先頭から何バイトを判定に使用するかを指定
* @return string 検出した文字コード (UTF-8, SJIS-win, ...)
* @throws CsvImportException ファイルの読み込みに失敗した、文字コードを判定できなかった、または非対応文字コードを検出した場合にスロー
*/
private function guessCharset(string $filename, int $samplingLength = 1024): string
{
$fp = fopen($filename, 'rb');
if (!$fp) {
throw new CsvImportException('CSVファイルの読み込み中にエラーが発生しました。');
}
try {
$head = fread($fp, $samplingLength);
if ($head === false) {
throw new CsvImportException('CSVファイルの読み込み中にエラーが発生しました。');
}
for ($addition = 0; $addition < 4; $addition++) {
$charset = mb_detect_encoding($head, ['ASCII', 'UTF-8', 'SJIS-win'], true);
if ($charset) {
if (array_search($charset, ['UTF-8', 'SJIS-win'], true) === false) {
throw new CsvImportException('文字コード判定に失敗しました。UTF-8 (BOM無し) または Shift_JIS をお使いください。');
} else {
return $charset;
}
}
// 1バイト追加で読み込んだら、文字境界に到達して上手く判定できるかもしれない
if (feof($fp)) {
break;
}
$next = fread($fp, 1);
if ($next === false) {
throw new CsvImportException('CSVファイルの読み込み中にエラーが発生しました。');
}
$head .= $next;
}
throw new CsvImportException('文字コード判定に失敗しました。UTF-8 (BOM無し) または Shift_JIS をお使いください。');
} finally {
fclose($fp);
}
}
/**
* タグ列をパースします。
* @param int $line 現在の行番号 (1 origin)
* @param array $record 対象行のデータ
* @return Tag[]
* @throws CsvImportException バリデーションエラーが発生した場合にスロー
*/
private function parseTags(int $line, array $record): array
{
$tags = [];
foreach (array_keys($record) as $column) {
if (preg_match('/\Aタグ\d{1,2}\z/u', $column) !== 1) {
continue;
}
$tag = trim($record[$column]);
if (empty($tag)) {
continue;
}
if (mb_strlen($tag) > 255) {
throw new CsvImportException("{$line} 行 : {$column}は255文字以内にしてください。");
}
if (strpos($tag, "\n") !== false) {
throw new CsvImportException("{$line} 行 : {$column}に改行を含めることはできません。");
}
if (strpos($tag, ' ') !== false) {
throw new CsvImportException("{$line} 行 : {$column}にスペースを含めることはできません。");
}
$tags[] = Tag::firstOrCreate(['name' => $tag]);
if (count($tags) >= 32) {
break;
}
}
return $tags;
}
}

View File

@ -32,6 +32,15 @@ class User extends Authenticatable
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
// 'email_verified_at' => 'datetime',
];
/**
* このユーザのメールアドレスから、Gravatarの画像URLを生成します。
* @param int $size 画像サイズ

View File

@ -2,6 +2,7 @@
namespace App\Utilities;
use Illuminate\Support\Str;
use Misd\Linkify\Linkify;
class Formatter
@ -55,10 +56,10 @@ class Formatter
$parts = parse_url($url);
if (!empty($parts['query'])) {
// Remove query parameters
$url = str_replace_last('?' . $parts['query'], '', $url);
$url = Str::replaceFirst('?' . $parts['query'], '', $url);
if (!empty($parts['fragment'])) {
// Remove fragment identifier
$url = str_replace_last('#' . $parts['fragment'], '', $url);
$url = Str::replaceFirst('#' . $parts['fragment'], '', $url);
} else {
// "http://example.com/?query#" の場合 $parts['fragment'] は unset になるので、個別に判定して除去する必要がある
$url = preg_replace('/#\z/u', '', $url);
@ -92,4 +93,43 @@ class Formatter
return implode(',', $srcset);
}
/**
* php.ini書式のデータサイズを正規化します。
* @param mixed $val データサイズ
* @return string
*/
public function normalizeIniBytes($val)
{
$val = trim($val);
$last = strtolower(substr($val, -1, 1));
if (ord($last) < 0x30 || ord($last) > 0x39) {
$bytes = substr($val, 0, -1);
switch ($last) {
case 'g':
$bytes *= 1024;
// fall through
// no break
case 'm':
$bytes *= 1024;
// fall through
// no break
case 'k':
$bytes *= 1024;
break;
}
} else {
$bytes = $val;
}
if ($bytes >= (1 << 30)) {
return ($bytes >> 30) . 'GB';
} elseif ($bytes >= (1 << 20)) {
return ($bytes >> 20) . 'MB';
} elseif ($bytes >= (1 << 10)) {
return ($bytes >> 10) . 'KB';
}
return $bytes . 'B';
}
}

View File

@ -12,7 +12,7 @@
*/
$app = new Illuminate\Foundation\Application(
realpath(__DIR__.'/../')
$_ENV['APP_BASE_PATH'] ?? dirname(__DIR__)
);
/*

View File

@ -4,16 +4,26 @@
"keywords": ["framework", "laravel"],
"license": "MIT",
"type": "project",
"repositories": [
{
"type": "vcs",
"url": "https://github.com/xcezx/Stream_Filter_Mbstring"
}
],
"require": {
"php": ">=7.1.0",
"php": "^7.2",
"anhskohbo/no-captcha": "^3.0",
"doctrine/dbal": "^2.9",
"fideloper/proxy": "~3.3",
"erusev/parsedown": "^1.7",
"fideloper/proxy": "^4.0",
"guzzlehttp/guzzle": "^6.3",
"jakeasmith/http_build_url": "^1.0",
"laravel/framework": "5.5.*",
"laravel/tinker": "~1.0",
"laravel/framework": "^6.2",
"laravel/helpers": "^1.2",
"laravel/tinker": "^2.0",
"league/csv": "^9.5",
"misd/linkify": "^1.1",
"openpear/stream_filter_mbstring": "dev-master",
"staudenmeir/eloquent-eager-limit": "^1.0",
"symfony/css-selector": "^4.3",
"symfony/dom-crawler": "^4.3"
@ -21,11 +31,12 @@
"require-dev": {
"barryvdh/laravel-debugbar": "^3.1",
"barryvdh/laravel-ide-helper": "^2.5",
"filp/whoops": "~2.0",
"facade/ignition": "^1.4",
"friendsofphp/php-cs-fixer": "^2.14",
"fzaninotto/faker": "~1.4",
"mockery/mockery": "~1.0",
"phpunit/phpunit": "~6.0",
"fzaninotto/faker": "^1.9.1",
"mockery/mockery": "^1.0",
"nunomaduro/collision": "^3.0",
"phpunit/phpunit": "^8.0",
"symfony/thanks": "^1.0"
},
"autoload": {
@ -46,11 +57,11 @@
"@php -r \"file_exists('.env') || copy('.env.example', '.env');\""
],
"post-create-project-cmd": [
"@php artisan key:generate"
"@php artisan key:generate --ansi"
],
"post-autoload-dump": [
"Illuminate\\Foundation\\ComposerScripts::postAutoloadDump",
"@php artisan package:discover"
"@php artisan package:discover --ansi"
],
"fix": [
"php-cs-fixer fix --config=.php_cs.dist"
@ -63,5 +74,12 @@
"preferred-install": "dist",
"sort-packages": true,
"optimize-autoloader": true
}
},
"extra": {
"laravel": {
"dont-discover": []
}
},
"minimum-stability": "dev",
"prefer-stable": true
}

2833
composer.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -38,7 +38,7 @@ return [
|
*/
'debug' => env('APP_DEBUG', false),
'debug' => (bool) env('APP_DEBUG', false),
/*
|--------------------------------------------------------------------------
@ -53,6 +53,8 @@ return [
'url' => env('APP_URL', 'http://localhost'),
'asset_url' => env('ASSET_URL', null),
/*
|--------------------------------------------------------------------------
| Application Timezone
@ -92,6 +94,19 @@ return [
'fallback_locale' => 'en',
/*
|--------------------------------------------------------------------------
| Faker Locale
|--------------------------------------------------------------------------
|
| This locale will be used by the Faker PHP library when generating fake
| data for your database seeds. For example, this will be used to get
| localized telephone numbers, street address information and more.
|
*/
'faker_locale' => 'en_US',
/*
|--------------------------------------------------------------------------
| Encryption Key
@ -107,23 +122,6 @@ return [
'cipher' => 'AES-256-CBC',
/*
|--------------------------------------------------------------------------
| Logging Configuration
|--------------------------------------------------------------------------
|
| Here you may configure the log settings for your application. Out of
| the box, Laravel uses the Monolog PHP logging library. This gives
| you a variety of powerful log handlers / formatters to utilize.
|
| Available Settings: "single", "daily", "syslog", "errorlog"
|
*/
'log' => env('APP_LOG', 'single'),
'log_level' => env('APP_LOG_LEVEL', 'debug'),
/*
|--------------------------------------------------------------------------
| Autoloaded Service Providers
@ -194,6 +192,7 @@ return [
'aliases' => [
'App' => Illuminate\Support\Facades\App::class,
'Arr' => Illuminate\Support\Arr::class,
'Artisan' => Illuminate\Support\Facades\Artisan::class,
'Auth' => Illuminate\Support\Facades\Auth::class,
'Blade' => Illuminate\Support\Facades\Blade::class,
@ -223,6 +222,7 @@ return [
'Schema' => Illuminate\Support\Facades\Schema::class,
'Session' => Illuminate\Support\Facades\Session::class,
'Storage' => Illuminate\Support\Facades\Storage::class,
'Str' => Illuminate\Support\Str::class,
'URL' => Illuminate\Support\Facades\URL::class,
'Validator' => Illuminate\Support\Facades\Validator::class,
'View' => Illuminate\Support\Facades\View::class,

View File

@ -44,6 +44,7 @@ return [
'api' => [
'driver' => 'token',
'provider' => 'users',
'hash' => false,
],
],
@ -96,7 +97,21 @@ return [
'provider' => 'users',
'table' => 'password_resets',
'expire' => 60,
'throttle' => 60,
],
],
/*
|--------------------------------------------------------------------------
| Password Confirmation Timeout
|--------------------------------------------------------------------------
|
| Here you may define the amount of seconds before a password confirmation
| times out and the user is prompted to re-enter their password via the
| confirmation screen. By default, the timeout lasts for three hours.
|
*/
'password_timeout' => 10800,
];

View File

@ -36,7 +36,8 @@ return [
'secret' => env('PUSHER_APP_SECRET'),
'app_id' => env('PUSHER_APP_ID'),
'options' => [
//
'cluster' => env('PUSHER_APP_CLUSTER'),
'useTLS' => true,
],
],

View File

@ -1,5 +1,7 @@
<?php
use Illuminate\Support\Str;
return [
/*
@ -11,7 +13,8 @@ return [
| using this caching library. This connection is used when another is
| not explicitly specified when executing a given caching function.
|
| Supported: "apc", "array", "database", "file", "memcached", "redis"
| Supported: "apc", "array", "database", "file",
| "memcached", "redis", "dynamodb"
|
*/
@ -57,7 +60,7 @@ return [
env('MEMCACHED_PASSWORD'),
],
'options' => [
// Memcached::OPT_CONNECT_TIMEOUT => 2000,
// Memcached::OPT_CONNECT_TIMEOUT => 2000,
],
'servers' => [
[
@ -70,7 +73,16 @@ return [
'redis' => [
'driver' => 'redis',
'connection' => 'default',
'connection' => 'cache',
],
'dynamodb' => [
'driver' => 'dynamodb',
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
'table' => env('DYNAMODB_CACHE_TABLE', 'cache'),
'endpoint' => env('DYNAMODB_ENDPOINT'),
],
],
@ -86,6 +98,6 @@ return [
|
*/
'prefix' => 'laravel',
'prefix' => env('CACHE_PREFIX', Str::slug(env('APP_NAME', 'laravel'), '_').'_cache'),
];

View File

@ -1,5 +1,7 @@
<?php
use Illuminate\Support\Str;
return [
/*
@ -35,12 +37,15 @@ return [
'sqlite' => [
'driver' => 'sqlite',
'url' => env('DATABASE_URL'),
'database' => env('DB_DATABASE', database_path('database.sqlite')),
'prefix' => '',
'foreign_key_constraints' => env('DB_FOREIGN_KEYS', true),
],
'mysql' => [
'driver' => 'mysql',
'url' => env('DATABASE_URL'),
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'forge'),
@ -50,12 +55,17 @@ return [
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
'prefix' => '',
'prefix_indexes' => true,
'strict' => true,
'engine' => null,
'options' => extension_loaded('pdo_mysql') ? array_filter([
PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
]) : [],
],
'pgsql' => [
'driver' => 'pgsql',
'url' => env('DATABASE_URL'),
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '5432'),
'database' => env('DB_DATABASE', 'forge'),
@ -63,12 +73,14 @@ return [
'password' => env('DB_PASSWORD', ''),
'charset' => 'utf8',
'prefix' => '',
'prefix_indexes' => true,
'schema' => 'public',
'sslmode' => 'prefer',
],
'sqlsrv' => [
'driver' => 'sqlsrv',
'url' => env('DATABASE_URL'),
'host' => env('DB_HOST', 'localhost'),
'port' => env('DB_PORT', '1433'),
'database' => env('DB_DATABASE', 'forge'),
@ -76,6 +88,7 @@ return [
'password' => env('DB_PASSWORD', ''),
'charset' => 'utf8',
'prefix' => '',
'prefix_indexes' => true,
],
],
@ -99,20 +112,34 @@ return [
|--------------------------------------------------------------------------
|
| Redis is an open source, fast, and advanced key-value store that also
| provides a richer set of commands than a typical key-value systems
| provides a richer body of commands than a typical key-value system
| such as APC or Memcached. Laravel makes it easy to dig right in.
|
*/
'redis' => [
'client' => 'predis',
'client' => env('REDIS_CLIENT', 'phpredis'),
'options' => [
'cluster' => env('REDIS_CLUSTER', 'redis'),
'prefix' => env('REDIS_PREFIX', Str::slug(env('APP_NAME', 'laravel'), '_').'_database_'),
],
'default' => [
'url' => env('REDIS_URL'),
'host' => env('REDIS_HOST', '127.0.0.1'),
'password' => env('REDIS_PASSWORD', null),
'port' => env('REDIS_PORT', 6379),
'database' => 0,
'port' => env('REDIS_PORT', '6379'),
'database' => env('REDIS_DB', '0'),
],
'cache' => [
'url' => env('REDIS_URL'),
'host' => env('REDIS_HOST', '127.0.0.1'),
'password' => env('REDIS_PASSWORD', null),
'port' => env('REDIS_PORT', '6379'),
'database' => env('REDIS_CACHE_DB', '1'),
],
],

View File

@ -37,7 +37,7 @@ return [
| may even configure multiple disks of the same driver. Defaults have
| been setup for each driver as an example of the required options.
|
| Supported Drivers: "local", "ftp", "s3", "rackspace"
| Supported Drivers: "local", "ftp", "sftp", "s3"
|
*/
@ -61,6 +61,8 @@ return [
'secret' => env('AWS_SECRET'),
'region' => env('AWS_REGION'),
'bucket' => env('AWS_BUCKET'),
'url' => env('AWS_URL'),
'endpoint' => env('AWS_ENDPOINT'),
],
],

52
config/hashing.php Normal file
View File

@ -0,0 +1,52 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Default Hash Driver
|--------------------------------------------------------------------------
|
| This option controls the default hash driver that will be used to hash
| passwords for your application. By default, the bcrypt algorithm is
| used; however, you remain free to modify this option if you wish.
|
| Supported: "bcrypt", "argon", "argon2id"
|
*/
'driver' => 'bcrypt',
/*
|--------------------------------------------------------------------------
| Bcrypt Options
|--------------------------------------------------------------------------
|
| Here you may specify the configuration options that should be used when
| passwords are hashed using the Bcrypt algorithm. This will allow you
| to control the amount of time it takes to hash the given password.
|
*/
'bcrypt' => [
'rounds' => env('BCRYPT_ROUNDS', 10),
],
/*
|--------------------------------------------------------------------------
| Argon Options
|--------------------------------------------------------------------------
|
| Here you may specify the configuration options that should be used when
| passwords are hashed using the Argon algorithm. These will allow you
| to control the amount of time it takes to hash the given password.
|
*/
'argon' => [
'memory' => 1024,
'threads' => 2,
'time' => 2,
],
];

102
config/logging.php Normal file
View File

@ -0,0 +1,102 @@
<?php
use Monolog\Handler\StreamHandler;
use Monolog\Handler\SyslogUdpHandler;
return [
/*
|--------------------------------------------------------------------------
| Default Log Channel
|--------------------------------------------------------------------------
|
| This option defines the default log channel that gets used when writing
| messages to the logs. The name specified in this option should match
| one of the channels defined in the "channels" configuration array.
|
*/
'default' => env('LOG_CHANNEL', 'stack'),
/*
|--------------------------------------------------------------------------
| Log Channels
|--------------------------------------------------------------------------
|
| Here you may configure the log channels for your application. Out of
| the box, Laravel uses the Monolog PHP logging library. This gives
| you a variety of powerful log handlers / formatters to utilize.
|
| Available Drivers: "single", "daily", "slack", "syslog",
| "errorlog", "monolog",
| "custom", "stack"
|
*/
'channels' => [
'stack' => [
'driver' => 'stack',
'channels' => ['single'],
],
'single' => [
'driver' => 'single',
'path' => storage_path('logs/laravel.log'),
'level' => 'debug',
],
'daily' => [
'driver' => 'daily',
'path' => storage_path('logs/laravel.log'),
'level' => 'debug',
'days' => 14,
],
'slack' => [
'driver' => 'slack',
'url' => env('LOG_SLACK_WEBHOOK_URL'),
'username' => 'Laravel Log',
'emoji' => ':boom:',
'level' => 'critical',
],
'papertrail' => [
'driver' => 'monolog',
'level' => 'debug',
'handler' => SyslogUdpHandler::class,
'handler_with' => [
'host' => env('PAPERTRAIL_URL'),
'port' => env('PAPERTRAIL_PORT'),
],
],
'stderr' => [
'driver' => 'monolog',
'handler' => StreamHandler::class,
'formatter' => env('LOG_STDERR_FORMATTER'),
'with' => [
'stream' => 'php://stderr',
],
],
'syslog' => [
'driver' => 'syslog',
'level' => 'debug',
],
'errorlog' => [
'driver' => 'errorlog',
'level' => 'debug',
],
'null' => [
'driver' => 'monolog',
'handler' => NullHandler::class,
],
'emergency' => [
'path' => storage_path('logs/laravel.log'),
],
],
];

View File

@ -11,8 +11,8 @@ return [
| sending of e-mail. You may specify which one you're using throughout
| your application here. By default, Laravel is setup for SMTP mail.
|
| Supported: "smtp", "sendmail", "mailgun", "mandrill", "ses",
| "sparkpost", "log", "array"
| Supported: "smtp", "sendmail", "mailgun", "ses",
| "postmark", "log", "array"
|
*/
@ -120,4 +120,17 @@ return [
],
],
/*
|--------------------------------------------------------------------------
| Log Channel
|--------------------------------------------------------------------------
|
| If you are using the "log" driver, you may specify the logging channel
| if you prefer to keep mail messages separate from other log entries
| for simpler reading. Otherwise, the default channel will be used.
|
*/
'log_channel' => env('MAIL_LOG_CHANNEL'),
];

View File

@ -4,14 +4,12 @@ return [
/*
|--------------------------------------------------------------------------
| Default Queue Driver
| Default Queue Connection Name
|--------------------------------------------------------------------------
|
| Laravel's queue API supports an assortment of back-ends via a single
| API, giving you convenient access to each back-end using the same
| syntax for each one. Here you may set the default queue driver.
|
| Supported: "sync", "database", "beanstalkd", "sqs", "redis", "null"
| syntax for every one. Here you may define a default connection.
|
*/
@ -26,6 +24,8 @@ return [
| is used by your application. A default configuration has been added
| for each back-end shipped with Laravel. You are free to add more.
|
| Drivers: "sync", "database", "beanstalkd", "sqs", "redis", "null"
|
*/
'connections' => [
@ -46,22 +46,24 @@ return [
'host' => 'localhost',
'queue' => 'default',
'retry_after' => 90,
'block_for' => 0,
],
'sqs' => [
'driver' => 'sqs',
'key' => 'your-public-key',
'secret' => 'your-secret-key',
'prefix' => 'https://sqs.us-east-1.amazonaws.com/your-account-id',
'queue' => 'your-queue-name',
'region' => 'us-east-1',
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'prefix' => env('SQS_PREFIX', 'https://sqs.us-east-1.amazonaws.com/your-account-id'),
'queue' => env('SQS_QUEUE', 'your-queue-name'),
'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
],
'redis' => [
'driver' => 'redis',
'connection' => 'default',
'queue' => 'default',
'queue' => env('REDIS_QUEUE', 'default'),
'retry_after' => 90,
'block_for' => null,
],
],
@ -78,6 +80,7 @@ return [
*/
'failed' => [
'driver' => env('QUEUE_FAILED_DRIVER', 'database'),
'database' => env('DB_CONNECTION', 'mysql'),
'table' => 'failed_jobs',
],

View File

@ -8,31 +8,26 @@ return [
|--------------------------------------------------------------------------
|
| This file is for storing the credentials for third party services such
| as Stripe, Mailgun, SparkPost and others. This file provides a sane
| default location for this type of information, allowing packages
| to have a conventional place to find your various credentials.
| as Mailgun, SparkPost and others. This file provides a sane default
| location for this type of information, allowing packages to have
| a conventional file to locate the various service credentials.
|
*/
'mailgun' => [
'domain' => env('MAILGUN_DOMAIN'),
'secret' => env('MAILGUN_SECRET'),
'endpoint' => env('MAILGUN_ENDPOINT', 'api.mailgun.net'),
],
'postmark' => [
'token' => env('POSTMARK_TOKEN'),
],
'ses' => [
'key' => env('SES_KEY'),
'secret' => env('SES_SECRET'),
'region' => 'us-east-1',
],
'sparkpost' => [
'secret' => env('SPARKPOST_SECRET'),
],
'stripe' => [
'model' => App\User::class,
'key' => env('STRIPE_KEY'),
'secret' => env('STRIPE_SECRET'),
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
],
];

View File

@ -1,5 +1,7 @@
<?php
use Illuminate\Support\Str;
return [
/*
@ -29,7 +31,7 @@ return [
|
*/
'lifetime' => 120,
'lifetime' => env('SESSION_LIFETIME', 120),
'expire_on_close' => false,
@ -70,7 +72,7 @@ return [
|
*/
'connection' => null,
'connection' => env('SESSION_CONNECTION', null),
/*
|--------------------------------------------------------------------------
@ -96,7 +98,7 @@ return [
|
*/
'store' => null,
'store' => env('SESSION_STORE', null),
/*
|--------------------------------------------------------------------------
@ -122,7 +124,10 @@ return [
|
*/
'cookie' => 'laravel_session',
'cookie' => env(
'SESSION_COOKIE',
Str::slug(env('APP_NAME', 'laravel'), '_').'_session'
),
/*
|--------------------------------------------------------------------------
@ -176,4 +181,19 @@ return [
'http_only' => true,
/*
|--------------------------------------------------------------------------
| Same-Site Cookies
|--------------------------------------------------------------------------
|
| This option determines how your cookies behave when cross-site requests
| take place, and can be used to mitigate CSRF attacks. By default, we
| do not enable this as other CSRF protection services are in place.
|
| Supported: "lax", "strict", "none"
|
*/
'same_site' => null,
];

View File

@ -28,6 +28,9 @@ return [
|
*/
'compiled' => realpath(storage_path('framework/views')),
'compiled' => env(
'VIEW_COMPILED_PATH',
realpath(storage_path('framework/views'))
),
];

1
database/.gitignore vendored
View File

@ -1 +1,2 @@
*.sqlite
*.sqlite-journal

View File

@ -8,5 +8,6 @@ $factory->define(Ejaculation::class, function (Faker $faker) {
return [
'ejaculated_date' => $faker->date('Y-m-d H:i:s'),
'note' => $faker->text,
'source' => Ejaculation::SOURCE_WEB,
];
});

View File

@ -1,6 +1,8 @@
<?php
/** @var \Illuminate\Database\Eloquent\Factory $factory */
use Illuminate\Support\Str;
$factory->define(App\User::class, function (Faker\Generator $faker) {
static $password;
@ -8,7 +10,7 @@ $factory->define(App\User::class, function (Faker\Generator $faker) {
'name' => substr($faker->userName, 0, 15),
'email' => $faker->unique()->safeEmail,
'password' => $password ?: $password = bcrypt('secret'),
'remember_token' => str_random(10),
'remember_token' => Str::random(10),
'display_name' => substr($faker->name, 0, 20),
'is_protected' => false,
'accept_analytics' => false,

View File

@ -0,0 +1,38 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class AddSourceToEjaculations extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('ejaculation_sources', function (Blueprint $table) {
$table->string('name');
$table->primary('name');
});
Schema::table('ejaculations', function (Blueprint $table) {
$table->string('source')->nullable();
$table->foreign('source')->references('name')->on('ejaculation_sources');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('ejaculations', function (Blueprint $table) {
$table->dropColumn('source');
});
Schema::drop('ejaculation_sources');
}
}

View File

@ -0,0 +1,34 @@
<?php
use App\Ejaculation;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class MakeNonNullableSourceOnEjaculations extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
DB::statement('UPDATE ejaculations SET source = ? WHERE source IS NULL', [Ejaculation::SOURCE_WEB]);
Schema::table('ejaculations', function (Blueprint $table) {
$table->string('source')->nullable(false)->change();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('ejaculations', function (Blueprint $table) {
$table->string('source')->nullable()->change();
});
}
}

View File

@ -5,12 +5,12 @@ use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
/**
* Run the database seeds.
* Seed the application's database.
*
* @return void
*/
public function run()
{
// $this->call(UsersTableSeeder::class);
$this->call(EjaculationSourcesSeeder::class);
}
}

View File

@ -0,0 +1,19 @@
<?php
use Illuminate\Database\Seeder;
class EjaculationSourcesSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$sources = ['web', 'csv'];
foreach ($sources as $source) {
DB::table('ejaculation_sources')->insert(['name' => $source]);
}
}
}

View File

@ -9,14 +9,14 @@
processIsolation="false"
stopOnFailure="false">
<testsuites>
<testsuite name="Feature">
<directory suffix="Test.php">./tests/Feature</directory>
</testsuite>
<testsuite name="Unit">
<directory suffix="Test.php">./tests/Unit</directory>
</testsuite>
<testsuite name="Feature">
<directory suffix="Test.php">./tests/Feature</directory>
</testsuite>
<testsuite name="MetadataResolver">
<directory suffix="Test.php">./tests/Unit/MetadataResolver</directory>
</testsuite>
@ -28,8 +28,10 @@
</filter>
<php>
<env name="APP_ENV" value="testing" force="true"/>
<env name="BCRYPT_ROUNDS" value="4" force="true"/>
<env name="CACHE_DRIVER" value="array" force="true"/>
<env name="SESSION_DRIVER" value="array" force="true"/>
<env name="QUEUE_DRIVER" value="sync" force="true"/>
<env name="MAIL_DRIVER" value="array" force="true"/>
</php>
</phpunit>

5
resources/assets/js/setting/import.js vendored Normal file
View File

@ -0,0 +1,5 @@
$('#destroy-form').on('submit', function () {
if (!confirm('本当に削除してもよろしいですか?')) {
return false;
}
});

15
resources/assets/js/user/profile.js vendored Normal file
View File

@ -0,0 +1,15 @@
import CalHeatMap from 'cal-heatmap';
if (document.getElementById('cal-heatmap')) {
new CalHeatMap().init({
itemSelector: '#cal-heatmap',
domain: 'month',
subDomain: 'day',
domainLabelFormat: '%Y/%m',
weekStartOnMonday: false,
start: new Date().setMonth(new Date().getMonth() - 9),
range: 10,
data: JSON.parse(document.getElementById('count-by-day').textContent),
legend: [1, 2, 3, 4]
});
}

View File

@ -1,6 +1,6 @@
import CalHeatMap from 'cal-heatmap';
import Chart from 'chart.js';
import {addMonths, format, startOfMonth, subMonths} from 'date-fns';
import {addMonths, format} from 'date-fns';
const graphData = JSON.parse(document.getElementById('graph-data').textContent);
@ -90,53 +90,35 @@ function createMonthlyGraphData(from) {
return {keys, values};
}
new CalHeatMap().init({
itemSelector: '#cal-heatmap',
domain: 'month',
subDomain: 'day',
domainLabelFormat: '%Y/%m',
weekStartOnMonday: false,
start: new Date().setMonth(new Date().getMonth() - 9),
range: 10,
data: graphData.dailySum,
legend: [1, 2, 3, 4]
});
// 直近1年の月間グラフのデータを準備
const monthlyTermFrom = subMonths(startOfMonth(new Date()), 11);
const {keys: monthlyKey, values: monthlySum} = createMonthlyGraphData(monthlyTermFrom);
const monthlyGraph = createLineGraph('monthly-graph', monthlyKey, monthlySum);
createLineGraph('yearly-graph', graphData.yearlyKey, graphData.yearlySum);
createBarGraph('hourly-graph', graphData.hourlyKey, graphData.hourlySum);
createBarGraph('dow-graph', ['日', '月', '火', '水', '木', '金', '土'], graphData.dowSum);
// 月間グラフの期間セレクターを準備
const monthlyTermSelector = document.getElementById('monthly-term');
const earliestYear = [...new Set(Object.keys(graphData.monthlySum).map(v => v.substr(0, 4)))].shift();
for (let year = earliestYear; year <= new Date().getFullYear(); year++) {
const opt = document.createElement('option');
opt.setAttribute('value', year);
opt.textContent = `${year}`;
monthlyTermSelector.insertBefore(opt, monthlyTermSelector.firstChild);
}
if (monthlyTermSelector.children.length) {
monthlyTermSelector.selectedIndex = 0;
function getCurrentYear() {
const year = location.pathname.split('/').pop();
return /^(20[0-9]{2})$/.test(year) ? year : null;
}
monthlyTermSelector.addEventListener('change', function (e) {
let monthlyTermFrom;
if (e.target.selectedIndex === 0) {
// 今年のデータを表示する時は、直近12ヶ月を表示
monthlyTermFrom = subMonths(startOfMonth(new Date()), 11);
} else {
// 過去のデータを表示する時は、選択年の1〜12月を表示
monthlyTermFrom = new Date(e.target.value, 0, 1);
}
if (document.getElementById('cal-heatmap')) {
new CalHeatMap().init({
itemSelector: '#cal-heatmap',
domain: 'month',
subDomain: 'day',
domainLabelFormat: '%Y/%m',
weekStartOnMonday: false,
start: new Date(getCurrentYear(), 0, 1, 0, 0, 0, 0),
range: 12,
data: graphData.dailySum,
legend: [1, 2, 3, 4]
});
}
const {keys, values} = createMonthlyGraphData(monthlyTermFrom);
monthlyGraph.data.labels = keys;
monthlyGraph.data.datasets[0].data = values;
monthlyGraph.update();
});
if (document.getElementById('monthly-graph')) {
const {keys: monthlyKey, values: monthlySum} = createMonthlyGraphData(new Date(getCurrentYear(), 0, 1, 0, 0, 0, 0));
createLineGraph('monthly-graph', monthlyKey, monthlySum);
}
if (document.getElementById('yearly-graph')) {
createLineGraph('yearly-graph', graphData.yearlyKey, graphData.yearlySum);
}
if (document.getElementById('hourly-graph')) {
createBarGraph('hourly-graph', graphData.hourlyKey, graphData.hourlySum);
}
if (document.getElementById('dow-graph')) {
createBarGraph('dow-graph', ['日', '月', '火', '水', '木', '金', '土'], graphData.dowSum);
}

View File

@ -13,9 +13,9 @@ return [
|
*/
'password' => 'Passwords must be at least six characters and match the confirmation.',
'reset' => 'Your password has been reset!',
'sent' => 'We have e-mailed your password reset link!',
'throttled' => 'Please wait before retrying.',
'token' => 'This password reset token is invalid.',
'user' => "We can't find a user with that e-mail address.",

View File

@ -13,80 +13,110 @@ return [
|
*/
'accepted' => 'The :attribute must be accepted.',
'active_url' => 'The :attribute is not a valid URL.',
'after' => 'The :attribute must be a date after :date.',
'after_or_equal' => 'The :attribute must be a date after or equal to :date.',
'alpha' => 'The :attribute may only contain letters.',
'alpha_dash' => 'The :attribute may only contain letters, numbers, and dashes.',
'alpha_num' => 'The :attribute may only contain letters and numbers.',
'array' => 'The :attribute must be an array.',
'before' => 'The :attribute must be a date before :date.',
'before_or_equal' => 'The :attribute must be a date before or equal to :date.',
'between' => [
'accepted' => 'The :attribute must be accepted.',
'active_url' => 'The :attribute is not a valid URL.',
'after' => 'The :attribute must be a date after :date.',
'after_or_equal' => 'The :attribute must be a date after or equal to :date.',
'alpha' => 'The :attribute may only contain letters.',
'alpha_dash' => 'The :attribute may only contain letters, numbers, dashes and underscores.',
'alpha_num' => 'The :attribute may only contain letters and numbers.',
'array' => 'The :attribute must be an array.',
'before' => 'The :attribute must be a date before :date.',
'before_or_equal' => 'The :attribute must be a date before or equal to :date.',
'between' => [
'numeric' => 'The :attribute must be between :min and :max.',
'file' => 'The :attribute must be between :min and :max kilobytes.',
'string' => 'The :attribute must be between :min and :max characters.',
'array' => 'The :attribute must have between :min and :max items.',
'file' => 'The :attribute must be between :min and :max kilobytes.',
'string' => 'The :attribute must be between :min and :max characters.',
'array' => 'The :attribute must have between :min and :max items.',
],
'boolean' => 'The :attribute field must be true or false.',
'confirmed' => 'The :attribute confirmation does not match.',
'date' => 'The :attribute is not a valid date.',
'date_format' => 'The :attribute does not match the format :format.',
'different' => 'The :attribute and :other must be different.',
'digits' => 'The :attribute must be :digits digits.',
'digits_between' => 'The :attribute must be between :min and :max digits.',
'dimensions' => 'The :attribute has invalid image dimensions.',
'distinct' => 'The :attribute field has a duplicate value.',
'email' => 'The :attribute must be a valid email address.',
'exists' => 'The selected :attribute is invalid.',
'file' => 'The :attribute must be a file.',
'filled' => 'The :attribute field must have a value.',
'image' => 'The :attribute must be an image.',
'in' => 'The selected :attribute is invalid.',
'in_array' => 'The :attribute field does not exist in :other.',
'integer' => 'The :attribute must be an integer.',
'ip' => 'The :attribute must be a valid IP address.',
'ipv4' => 'The :attribute must be a valid IPv4 address.',
'ipv6' => 'The :attribute must be a valid IPv6 address.',
'json' => 'The :attribute must be a valid JSON string.',
'max' => [
'boolean' => 'The :attribute field must be true or false.',
'confirmed' => 'The :attribute confirmation does not match.',
'date' => 'The :attribute is not a valid date.',
'date_equals' => 'The :attribute must be a date equal to :date.',
'date_format' => 'The :attribute does not match the format :format.',
'different' => 'The :attribute and :other must be different.',
'digits' => 'The :attribute must be :digits digits.',
'digits_between' => 'The :attribute must be between :min and :max digits.',
'dimensions' => 'The :attribute has invalid image dimensions.',
'distinct' => 'The :attribute field has a duplicate value.',
'email' => 'The :attribute must be a valid email address.',
'ends_with' => 'The :attribute must end with one of the following: :values.',
'exists' => 'The selected :attribute is invalid.',
'file' => 'The :attribute must be a file.',
'filled' => 'The :attribute field must have a value.',
'gt' => [
'numeric' => 'The :attribute must be greater than :value.',
'file' => 'The :attribute must be greater than :value kilobytes.',
'string' => 'The :attribute must be greater than :value characters.',
'array' => 'The :attribute must have more than :value items.',
],
'gte' => [
'numeric' => 'The :attribute must be greater than or equal :value.',
'file' => 'The :attribute must be greater than or equal :value kilobytes.',
'string' => 'The :attribute must be greater than or equal :value characters.',
'array' => 'The :attribute must have :value items or more.',
],
'image' => 'The :attribute must be an image.',
'in' => 'The selected :attribute is invalid.',
'in_array' => 'The :attribute field does not exist in :other.',
'integer' => 'The :attribute must be an integer.',
'ip' => 'The :attribute must be a valid IP address.',
'ipv4' => 'The :attribute must be a valid IPv4 address.',
'ipv6' => 'The :attribute must be a valid IPv6 address.',
'json' => 'The :attribute must be a valid JSON string.',
'lt' => [
'numeric' => 'The :attribute must be less than :value.',
'file' => 'The :attribute must be less than :value kilobytes.',
'string' => 'The :attribute must be less than :value characters.',
'array' => 'The :attribute must have less than :value items.',
],
'lte' => [
'numeric' => 'The :attribute must be less than or equal :value.',
'file' => 'The :attribute must be less than or equal :value kilobytes.',
'string' => 'The :attribute must be less than or equal :value characters.',
'array' => 'The :attribute must not have more than :value items.',
],
'max' => [
'numeric' => 'The :attribute may not be greater than :max.',
'file' => 'The :attribute may not be greater than :max kilobytes.',
'string' => 'The :attribute may not be greater than :max characters.',
'array' => 'The :attribute may not have more than :max items.',
'file' => 'The :attribute may not be greater than :max kilobytes.',
'string' => 'The :attribute may not be greater than :max characters.',
'array' => 'The :attribute may not have more than :max items.',
],
'mimes' => 'The :attribute must be a file of type: :values.',
'mimetypes' => 'The :attribute must be a file of type: :values.',
'min' => [
'mimes' => 'The :attribute must be a file of type: :values.',
'mimetypes' => 'The :attribute must be a file of type: :values.',
'min' => [
'numeric' => 'The :attribute must be at least :min.',
'file' => 'The :attribute must be at least :min kilobytes.',
'string' => 'The :attribute must be at least :min characters.',
'array' => 'The :attribute must have at least :min items.',
'file' => 'The :attribute must be at least :min kilobytes.',
'string' => 'The :attribute must be at least :min characters.',
'array' => 'The :attribute must have at least :min items.',
],
'not_in' => 'The selected :attribute is invalid.',
'numeric' => 'The :attribute must be a number.',
'present' => 'The :attribute field must be present.',
'regex' => 'The :attribute format is invalid.',
'required' => 'The :attribute field is required.',
'required_if' => 'The :attribute field is required when :other is :value.',
'required_unless' => 'The :attribute field is required unless :other is in :values.',
'required_with' => 'The :attribute field is required when :values is present.',
'required_with_all' => 'The :attribute field is required when :values is present.',
'required_without' => 'The :attribute field is required when :values is not present.',
'not_in' => 'The selected :attribute is invalid.',
'not_regex' => 'The :attribute format is invalid.',
'numeric' => 'The :attribute must be a number.',
'password' => 'The password is incorrect.',
'present' => 'The :attribute field must be present.',
'regex' => 'The :attribute format is invalid.',
'required' => 'The :attribute field is required.',
'required_if' => 'The :attribute field is required when :other is :value.',
'required_unless' => 'The :attribute field is required unless :other is in :values.',
'required_with' => 'The :attribute field is required when :values is present.',
'required_with_all' => 'The :attribute field is required when :values are present.',
'required_without' => 'The :attribute field is required when :values is not present.',
'required_without_all' => 'The :attribute field is required when none of :values are present.',
'same' => 'The :attribute and :other must match.',
'size' => [
'same' => 'The :attribute and :other must match.',
'size' => [
'numeric' => 'The :attribute must be :size.',
'file' => 'The :attribute must be :size kilobytes.',
'string' => 'The :attribute must be :size characters.',
'array' => 'The :attribute must contain :size items.',
'file' => 'The :attribute must be :size kilobytes.',
'string' => 'The :attribute must be :size characters.',
'array' => 'The :attribute must contain :size items.',
],
'string' => 'The :attribute must be a string.',
'timezone' => 'The :attribute must be a valid zone.',
'unique' => 'The :attribute has already been taken.',
'uploaded' => 'The :attribute failed to upload.',
'url' => 'The :attribute format is invalid.',
'starts_with' => 'The :attribute must start with one of the following: :values.',
'string' => 'The :attribute must be a string.',
'timezone' => 'The :attribute must be a valid zone.',
'unique' => 'The :attribute has already been taken.',
'uploaded' => 'The :attribute failed to upload.',
'url' => 'The :attribute format is invalid.',
'uuid' => 'The :attribute must be a valid UUID.',
/*
|--------------------------------------------------------------------------
@ -110,9 +140,9 @@ return [
| Custom Validation Attributes
|--------------------------------------------------------------------------
|
| The following language lines are used to swap attribute place-holders
| with something more reader friendly such as E-Mail Address instead
| of "email". This simply helps us make messages a little cleaner.
| The following language lines are used to swap our attribute placeholder
| with something more reader friendly such as "E-Mail Address" instead
| of "email". This simply helps us make our message more expressive.
|
*/

View File

@ -6,11 +6,14 @@
</h5>
</div>
<!-- tags -->
@if ($ejaculation->is_private || $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
@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

@ -0,0 +1,14 @@
<div class="d-flex flex-row align-items-end {{ $class ?? '' }}">
<img src="{{ $user->getProfileImageUrl(48) }}" srcset="{{ Formatter::profileImageSrcSet($user, 48) }}" class="rounded mr-2">
<div class="d-flex flex-column overflow-hidden">
<h5 class="card-title text-truncate">
<a class="text-dark" href="{{ route('user.profile', ['name' => $user->name]) }}">{{ $user->display_name }}</a>
</h5>
<h6 class="card-subtitle">
<a class="text-muted" href="{{ route('user.profile', ['name' => $user->name]) }}">&commat;{{ $user->name }}</a>
@if ($user->is_protected)
<span class="oi oi-lock-locked text-muted"></span>
@endif
</h6>
</div>
</div>

View File

@ -98,6 +98,7 @@
<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>
</div>
</div>
</div>

View File

@ -34,11 +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->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
@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

@ -0,0 +1,38 @@
@extends('layouts.base')
@section('title', 'ブックマークレットについて')
@section('content')
<div class="container">
<h2>ブックマークレットと共有機能について</h2>
<hr>
<div class="row">
<div class="col-lg-10">
<p>以下のブックマークレットを使うと、ブラウザで現在見ているページで簡単にチェックインすることができます。</p>
<div class="card mb-4">
<div class="card-body">
<pre class="mb-0"><code>javascript:location.href='{{ url('/') }}/checkin?link='+encodeURIComponent(location.href)</code></pre>
</div>
</div>
<p>また、<a href="https://www.chromestatus.com/feature/5662315307335680">Web Share Target</a> に対応しているブラウザでは、他のWebサイトやアプリからURLを「共有」することができます。</p>
<ul>
<li>Android版 Google Chrome の場合
<ul>
<li>画面下に出てくる「ホーム画面に Tissue を追加」、もしくは右上のメニューからインストール</li>
<li>任意のアプリからURLを共有 Tissue を選択 チェックイン画面</li>
</ul>
</li>
</ul>
<p> Web Share Target の仕様はまだドラフト段階で、今後仕様の変更により動かなくなる場合があります。</p>
</div>
</div>
<h2 class="mt-4">高度な使い方</h2>
<hr>
<div class="row">
<div class="col-lg-10">
<p>チェックイン画面のURLにクエリパラメータを付加することで、各フィールドに値をセットした状態で開くことができます。</p>
<p>: <a href="{{ url('checkin?date=1900/01/01&time=00:00&tags=blah+blur&link=hoge&note=piyo') }}">{{ url('checkin?date=1900/01/01&time=00:00&tags=blah+blur&link=hoge&note=piyo') }}</a></p>
</div>
</div>
</div>
@endsection

View File

@ -9,20 +9,8 @@
<div class="col-lg-4">
<div class="card mb-4">
<div class="card-body">
<div class="d-flex flex-row align-items-end mb-4">
<img src="{{ Auth::user()->getProfileImageUrl(48) }}" srcset="{{ Formatter::profileImageSrcSet(Auth::user(), 48) }}" class="rounded mr-2">
<div class="d-flex flex-column overflow-hidden">
<h5 class="card-title text-truncate">
<a class="text-dark" href="{{ route('user.profile', ['name' => Auth::user()->name]) }}">{{ Auth::user()->display_name }}</a>
</h5>
<h6 class="card-subtitle">
<a class="text-muted" href="{{ route('user.profile', ['name' => Auth::user()->name]) }}">&commat;{{ Auth::user()->name }}</a>
@if (Auth::user()->is_protected)
<span class="oi oi-lock-locked text-muted"></span>
@endif
</h6>
</div>
</div>
@component('components.profile-mini', ['user' => Auth::user(), 'class' => 'mb-4'])
@endcomponent
@component('components.profile-stats', ['user' => Auth::user()])
@endcomponent
</div>

View File

@ -10,6 +10,10 @@
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.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' : '' }}"
href="{{ route('setting.export') }}"><span class="oi oi-data-transfer-download mr-1"></span> データのエクスポート</a>
<a class="list-group-item list-group-item-action {{ Route::currentRouteName() === 'setting.deactivate' ? 'active' : '' }}"
href="{{ route('setting.deactivate') }}"><span class="oi oi-trash mr-1"></span> アカウントの削除</a>
{{--<a class="list-group-item list-group-item-action {{ Route::currentRouteName() === 'setting.password' ? 'active' : '' }}"

View File

@ -0,0 +1,27 @@
@extends('setting.base')
@section('title', 'データのエクスポート')
@section('tab-content')
<h3>データのエクスポート</h3>
<hr>
<p>チェックインデータをCSVファイルとしてダウンロードすることができます。</p>
<form class="mt-4" action="{{ route('setting.export.csv') }}" method="get">
{{ csrf_field() }}
<div class="mb-2"><strong>文字コード</strong></div>
<div class="form-group">
<div class="custom-control custom-radio custom-control-inline">
<input id="charsetUTF8" class="custom-control-input" type="radio" name="charset" value="utf8" checked>
<label for="charsetUTF8" class="custom-control-label">UTF-8</label>
</div>
<div class="custom-control custom-radio custom-control-inline ml-3">
<input id="charsetSJIS" class="custom-control-input" type="radio" name="charset" value="sjis">
<label for="charsetSJIS" class="custom-control-label">Shift_JIS</label>
</div>
</div>
<button type="submit" class="btn btn-primary mt-3">ダウンロード</button>
</form>
@endsection
@push('script')
@endpush

View File

@ -0,0 +1,42 @@
@extends('setting.base')
@section('title', 'データのインポート')
@section('tab-content')
<h3>データのインポート</h3>
<hr>
<p>外部で作成したチェックインデータをTissueに取り込むことができます。</p>
<form class="mt-4" action="{{ route('setting.import') }}" method="post" enctype="multipart/form-data">
{{ csrf_field() }}
<div class="form-group">
<strong>取り込むファイルを選択してください。</strong>
<small class="form-text text-muted">{{ Formatter::normalizeIniBytes(ini_get('upload_max_filesize')) }}までのCSVファイル、文字コードは Shift_JIS UTF-8 (BOMなし) に対応しています。</small>
<input name="file" type="file" class="form-control-file {{ $errors->has('file') ? ' is-invalid' : '' }} mt-2">
@if ($errors->has('file'))
<div class="invalid-feedback">{{ $errors->first('file') }}</div>
@endif
</div>
@if (session('import_errors'))
<div class="alert alert-danger">
<p class="alert-heading"><span class="oi oi-warning"></span> <strong>インポートに失敗しました</strong></p>
@foreach (session('import_errors') as $err)
<p class="mb-0">{{ $err }}</p>
@endforeach
</div>
@endif
<button type="submit" class="btn btn-primary mt-2">アップロード</button>
</form>
<h3 class="mt-5">インポートしたデータを一括削除</h3>
<hr>
<p class="mb-0">取り込んだチェックインデータをすべて削除することができます。データにミスがあってやり直したい場合などにお使いください。</p>
<p class="text-danger">ただし、インポート後に個別に手修正などしている場合、そのデータも失われてしまうことに注意してください!</p>
<form id="destroy-form" class="mt-4" action="{{ route('setting.import.destroy') }}" method="post">
{{ csrf_field() }}
{{ method_field('DELETE') }}
<button type="submit" class="btn btn-danger mt-2">データを削除</button>
</form>
@endsection
@push('script')
<script src="{{ mix('js/setting/import.js') }}"></script>
@endpush

View File

@ -4,8 +4,17 @@
<div class="container">
<div class="row">
<div class="col-lg-4">
@component('components.profile', ['user' => $user])
@endcomponent
@if (Route::currentRouteName() === 'user.profile')
@component('components.profile', ['user' => $user])
@endcomponent
@else
<div class="card mb-4">
<div class="card-body">
@component('components.profile-mini', ['user' => $user])
@endcomponent
</div>
</div>
@endif
@section('sidebar')
@show
</div>
@ -15,7 +24,7 @@
<a class="nav-link {{ Route::currentRouteName() === 'user.profile' ? 'active' : '' }}" href="{{ route('user.profile', ['name' => $user->name]) }}">タイムライン</a>
</li>
<li class="nav-item">
<a class="nav-link {{ Route::currentRouteName() === 'user.stats' ? 'active' : '' }}" href="{{ route('user.stats', ['name' => $user->name]) }}">グラフ</a>
<a class="nav-link {{ stripos(Route::currentRouteName(), 'user.stats') === 0 ? 'active' : '' }}" href="{{ route('user.stats', ['name' => $user->name]) }}">グラフ</a>
</li>
<li class="nav-item">
<a class="nav-link {{ Route::currentRouteName() === 'user.okazu' ? 'active' : '' }}" href="{{ route('user.okazu', ['name' => $user->name]) }}">オカズ</a>

View File

@ -2,6 +2,12 @@
@section('title', $user->display_name . ' (@' . $user->name . ')')
@push('head')
@if (Route::currentRouteName() === 'user.profile')
<link rel="stylesheet" href="//cdn.jsdelivr.net/cal-heatmap/3.3.10/cal-heatmap.css" />
@endif
@endpush
@section('sidebar')
{{-- TODO: タイムラインとオカズのテンプレを分けたら条件外す --}}
@if (Route::currentRouteName() === 'user.profile')
@ -32,6 +38,11 @@
<span class="oi oi-lock-locked"></span> このユーザはチェックイン履歴を公開していません。
</p>
@else
@if ($ejaculations->count() !== 0 && $ejaculations->currentPage() === 1)
<h5 class="mx-4 my-3">Shikontributions</h5>
<div id="cal-heatmap" class="tis-contribution-graph mx-4 mt-3"></div>
<hr class="mt-4 mb-2">
@endif
<ul class="list-group">
@forelse ($ejaculations as $ejaculation)
<li class="list-group-item border-bottom-only pt-3 pb-3 text-break">
@ -40,11 +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->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
@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
@ -113,3 +127,10 @@
@endslot
@endcomponent
@endsection
@push('script')
<script id="count-by-day" type="application/json">@json($countByDay)</script>
<script src="{{ mix('js/vendor/chart.js') }}"></script>
<script src="{{ mix('js/user/profile.js') }}"></script>
@endpush

View File

@ -0,0 +1,70 @@
@extends('user.base')
@section('sidebar')
@if (!$user->is_protected || $user->isMe())
<div class="nav d-none d-lg-flex flex-column nav-pills" aria-orientation="vertical">
<a class="nav-link {{ Route::currentRouteName() === 'user.stats' ? 'active' : '' }}"
href="{{ route('user.stats', ['name' => $user->name]) }}">全期間</a>
@foreach ($availableMonths as $year => $months)
<div class="border-top mt-1">
<a class="nav-link mt-1 {{ Route::currentRouteName() === 'user.stats.yearly' && $currentYear === $year ? 'active' : '' }}"
href="{{ route('user.stats.yearly', ['name' => $user->name, 'year' => $year]) }}">{{ $year }}</a>
@foreach ($months as $month)
<a class="nav-link ml-3 {{ Route::currentRouteName() === 'user.stats.monthly' && $currentYear === $year && $currentMonth === $month ? 'active' : '' }}"
href="{{ route('user.stats.monthly', ['name' => $user->name, 'year' => $year, 'month' => $month]) }}">{{ $month }}</a>
@endforeach
</div>
@endforeach
</div>
@endif
@endsection
@section('tab-content')
@if ($user->is_protected && !$user->isMe())
<p class="mt-4">
<span class="oi oi-lock-locked"></span> このユーザはチェックイン履歴を公開していません。
</p>
@else
<div class="row my-2 d-lg-none">
<div class="col-12 text-secondary font-weight-bold small">グラフの対象期間</div>
<div class="col-6 text-secondary small"></div>
<div class="col-6 text-secondary small"></div>
<div class="col-12">
<ul class="nav nav-pills nav-fill">
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">
{{ Route::currentRouteName() === 'user.stats' ? '全期間' : "{$currentYear}" }}
</a>
<div class="dropdown-menu">
<a href="{{ route('user.stats', ['name' => $user->name]) }}" class="dropdown-item">全期間</a>
@foreach ($availableMonths as $year => $months)
<a href="{{ route('user.stats.yearly', ['name' => $user->name, 'year' => $year]) }}" class="dropdown-item">{{ $year }}</a>
@endforeach
</div>
</li>
@if (Route::currentRouteName() === 'user.stats')
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle disabled"
href="#" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">全期間</a>
</li>
@else
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle"
href="#" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">
{{ Route::currentRouteName() === 'user.stats.yearly' ? '全期間' : "{$currentMonth}" }}
</a>
<div class="dropdown-menu">
<a href="{{ route('user.stats.yearly', ['name' => $user->name, 'year' => $currentYear]) }}" class="dropdown-item">全期間</a>
@foreach ($availableMonths[$currentYear] as $month)
<a href="{{ route('user.stats.monthly', ['name' => $user->name, 'year' => $currentYear, 'month' => $month]) }}" class="dropdown-item">{{ $month }}</a>
@endforeach
</div>
</li>
@endif
</ul>
</div>
</div>
<div class="row d-lg-none no-gutters border-bottom"></div>
@yield('stats-content')
@endif
@endsection

View File

@ -0,0 +1,20 @@
@extends('user.stats.base')
@section('title', $user->display_name . ' さんのグラフ')
@section('stats-content')
<h5 class="my-4">年間チェックイン回数</h5>
<canvas id="yearly-graph" class="w-100"></canvas>
<hr class="my-4">
<h5 class="my-4">時間別チェックイン回数</h5>
<canvas id="hourly-graph" class="w-100"></canvas>
<hr class="my-4">
<h5 class="my-4">曜日別チェックイン回数</h5>
<canvas id="dow-graph" class="w-100"></canvas>
@endsection
@push('script')
<script id="graph-data" type="application/json">@json($graphData)</script>
<script src="{{ mix('js/vendor/chart.js') }}"></script>
<script src="{{ mix('js/user/stats.js') }}"></script>
@endpush

View File

@ -0,0 +1,17 @@
@extends('user.stats.base')
@section('title', $user->display_name . ' さんのグラフ')
@section('stats-content')
<h5 class="my-4">時間別チェックイン回数</h5>
<canvas id="hourly-graph" class="w-100"></canvas>
<hr class="my-4">
<h5 class="my-4">曜日別チェックイン回数</h5>
<canvas id="dow-graph" class="w-100"></canvas>
@endsection
@push('script')
<script id="graph-data" type="application/json">@json($graphData)</script>
<script src="{{ mix('js/vendor/chart.js') }}"></script>
<script src="{{ mix('js/user/stats.js') }}"></script>
@endpush

View File

@ -1,4 +1,4 @@
@extends('user.base')
@extends('user.stats.base')
@section('title', $user->display_name . ' さんのグラフ')
@ -6,34 +6,18 @@
<link rel="stylesheet" href="//cdn.jsdelivr.net/cal-heatmap/3.3.10/cal-heatmap.css" />
@endpush
@section('tab-content')
@if ($user->is_protected && !$user->isMe())
<p class="mt-4">
<span class="oi oi-lock-locked"></span> このユーザはチェックイン履歴を公開していません。
</p>
@else
@section('stats-content')
<h5 class="my-4">Shikontribution graph</h5>
<div id="cal-heatmap" class="tis-contribution-graph"></div>
<hr class="my-4">
<div class="row my-4">
<div class="col-12 col-lg-6 d-flex align-items-center">
<h5 class="my-0">月間チェックイン回数</h5>
</div>
<div class="col-12 col-lg-6 mt-2 mt-lg-0">
<select id="monthly-term" class="form-control"></select>
</div>
</div>
<h5 class="my-4">月間チェックイン回数</h5>
<canvas id="monthly-graph" class="w-100"></canvas>
<hr class="my-4">
<h5 class="my-4">年間チェックイン回数</h5>
<canvas id="yearly-graph" class="w-100"></canvas>
<hr class="my-4">
<h5 class="my-4">時間別チェックイン回数</h5>
<canvas id="hourly-graph" class="w-100"></canvas>
<hr class="my-4">
<h5 class="my-4">曜日別チェックイン回数</h5>
<canvas id="dow-graph" class="w-100"></canvas>
@endif
@endsection
@push('script')

View File

@ -18,10 +18,13 @@ Route::get('/', 'HomeController@index')->name('home');
Route::get('/user', 'UserController@redirectMypage')->middleware('auth');
Route::get('/user/{name?}', 'UserController@profile')->name('user.profile');
Route::get('/user/{name}/stats', 'UserController@stats')->name('user.stats');
Route::get('/user/{name}/stats/{year}', 'UserController@statsYearly')->name('user.stats.yearly');
Route::get('/user/{name}/stats/{year}/{month}', 'UserController@statsMonthly')->name('user.stats.monthly');
Route::get('/user/{name}/okazu', 'UserController@okazu')->name('user.okazu');
Route::get('/user/{name}/likes', 'UserController@likes')->name('user.likes');
Route::get('/checkin/{id}', 'EjaculationController@show')->name('checkin.show');
Route::get('/checkin-tools', 'EjaculationController@tools')->name('checkin.tools');
Route::middleware('auth')->group(function () {
Route::get('/checkin', 'EjaculationController@create')->name('checkin');
Route::post('/checkin', 'EjaculationController@store')->name('checkin');
@ -36,6 +39,11 @@ 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/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');
Route::get('/setting/export', 'SettingController@export')->name('setting.export');
Route::get('/setting/export/csv', 'SettingController@exportToCsv')->name('setting.export.csv');
Route::get('/setting/deactivate', 'SettingController@deactivate')->name('setting.deactivate');
Route::post('/setting/deactivate', 'SettingController@destroyUser')->name('setting.deactivate.destroy');
// Route::get('/setting/password', 'SettingController@password')->name('setting.password');

View File

@ -1,2 +1,3 @@
*
!data/
!.gitignore

View File

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

View File

@ -13,6 +13,14 @@ use Tests\TestCase;
class SettingTest extends TestCase
{
use RefreshDatabase;
protected function setUp(): void
{
parent::setUp();
$this->seed();
}
public function testDestroyUser()
{
$user = factory(User::class)->create();

View File

@ -9,7 +9,7 @@ class CienResolverTest extends TestCase
{
use CreateMockedResolver;
public function setUp()
public function setUp(): void
{
parent::setUp();

View File

@ -9,7 +9,7 @@ class DLsiteResolverTest extends TestCase
{
use CreateMockedResolver;
public function setUp()
public function setUp(): void
{
parent::setUp();

View File

@ -9,7 +9,7 @@ class DeviantArtResolverTest extends TestCase
{
use CreateMockedResolver;
public function setUp()
public function setUp(): void
{
parent::setUp();

View File

@ -9,7 +9,7 @@ class FC2ContentsResolverTest extends TestCase
{
use CreateMockedResolver;
public function setUp()
public function setUp(): void
{
parent::setUp();

View File

@ -9,7 +9,7 @@ class FantiaResolverTest extends TestCase
{
use CreateMockedResolver;
public function setUp()
public function setUp(): void
{
parent::setUp();

View File

@ -9,7 +9,7 @@ class FanzaResolverTest extends TestCase
{
use CreateMockedResolver;
public function setUp()
public function setUp(): void
{
parent::setUp();

View File

@ -9,7 +9,7 @@ class HentaiFoundryResolverTest extends TestCase
{
use CreateMockedResolver;
public function setUp()
public function setUp(): void
{
parent::setUp();

View File

@ -9,7 +9,7 @@ class IwaraResolverTest extends TestCase
{
use CreateMockedResolver;
public function setUp()
public function setUp(): void
{
parent::setUp();

View File

@ -9,7 +9,7 @@ class Kb10uyShortStoryServerResolverTest extends TestCase
{
use CreateMockedResolver;
public function setUp()
public function setUp(): void
{
parent::setUp();

View File

@ -9,7 +9,7 @@ class KomifloResolverTest extends TestCase
{
use CreateMockedResolver;
public function setUp()
public function setUp(): void
{
parent::setUp();

View File

@ -10,7 +10,7 @@ class NicoSeigaResolverTest extends TestCase
{
use CreateMockedResolver, MyAsserts;
public function setUp()
public function setUp(): void
{
parent::setUp();

View File

@ -9,7 +9,7 @@ class NijieResolverTest extends TestCase
{
use CreateMockedResolver;
public function setUp()
public function setUp(): void
{
parent::setUp();

View File

@ -9,7 +9,7 @@ class PixivResolverTest extends TestCase
{
use CreateMockedResolver;
public function setUp()
public function setUp(): void
{
parent::setUp();

View File

@ -9,7 +9,7 @@ class PlurkResolverTest extends TestCase
{
use CreateMockedResolver;
public function setUp()
public function setUp(): void
{
parent::setUp();

View File

@ -9,7 +9,7 @@ class SteamResolverTest extends TestCase
{
use CreateMockedResolver;
public function setUp()
public function setUp(): void
{
parent::setUp();

View File

@ -9,7 +9,7 @@ class ToranoanaResolverTest extends TestCase
{
use CreateMockedResolver;
public function setUp()
public function setUp(): void
{
parent::setUp();

View File

@ -9,7 +9,7 @@ class XtubeResolverTest extends TestCase
{
use CreateMockedResolver;
public function setUp()
public function setUp(): void
{
parent::setUp();

View File

@ -0,0 +1,309 @@
<?php
declare(strict_types=1);
namespace Tests\Unit\Services;
use App\Ejaculation;
use App\Exceptions\CsvImportException;
use App\Services\CheckinCsvImporter;
use App\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Carbon;
use Tests\TestCase;
class CheckinCsvImporterTest extends TestCase
{
use RefreshDatabase;
protected function setUp(): void
{
parent::setUp();
$this->seed();
}
public function testIncompatibleCharsetEUCJP()
{
$user = factory(User::class)->create();
$this->expectException(CsvImportException::class);
$this->expectExceptionMessage('文字コード判定に失敗しました。UTF-8 (BOM無し) または Shift_JIS をお使いください。');
$importer = new CheckinCsvImporter($user, __DIR__ . '/../../fixture/Csv/incompatible-charset.eucjp.csv');
$importer->execute();
}
/**
* @dataProvider provideMissingTime
*/
public function testMissingTime($filename)
{
$user = factory(User::class)->create();
$this->expectException(CsvImportException::class);
$this->expectExceptionMessage('日時列は必須です。');
$importer = new CheckinCsvImporter($user, $filename);
$importer->execute();
}
public function provideMissingTime()
{
return [
'UTF8' => [__DIR__ . '/../../fixture/Csv/missing-time.utf8.csv'],
'SJIS' => [__DIR__ . '/../../fixture/Csv/missing-time.sjis.csv'],
];
}
/**
* @dataProvider provideDate
*/
public function testDate($expectedDate, $filename)
{
$user = factory(User::class)->create();
$importer = new CheckinCsvImporter($user, $filename);
$importer->execute();
$ejaculation = $user->ejaculations()->first();
$this->assertSame(1, $user->ejaculations()->count());
$this->assertEquals($expectedDate, $ejaculation->ejaculated_date);
}
public function provideDate()
{
$date = Carbon::create(2020, 1, 23, 6, 1, 0, 'Asia/Tokyo');
return [
'Zero, Second, UTF8' => [$date, __DIR__ . '/../../fixture/Csv/date.utf8.csv'],
'NoZero, Second, UTF8' => [$date, __DIR__ . '/../../fixture/Csv/date-nozero.utf8.csv'],
'Zero, NoSecond, UTF8' => [$date, __DIR__ . '/../../fixture/Csv/date-nosecond.utf8.csv'],
'NoZero, NoSecond, UTF8' => [$date, __DIR__ . '/../../fixture/Csv/date-nozero-nosecond.utf8.csv'],
];
}
public function testInvalidDate()
{
$user = factory(User::class)->create();
try {
$importer = new CheckinCsvImporter($user, __DIR__ . '/../../fixture/Csv/invalid-date.utf8.csv');
$importer->execute();
} catch (CsvImportException $e) {
$this->assertSame('2 行 : 日時は 2000/01/01 00:00 〜 2099/12/31 23:59 の間のみ対応しています。', $e->getErrors()[0]);
$this->assertSame('3 行 : 日時は 2000/01/01 00:00 〜 2099/12/31 23:59 の間のみ対応しています。', $e->getErrors()[1]);
$this->assertSame('4 行 : 日時の形式は "年/月/日 時:分" にしてください。', $e->getErrors()[2]);
$this->assertSame('5 行 : 日時の形式は "年/月/日 時:分" にしてください。', $e->getErrors()[3]);
$this->assertSame('6 行 : 日時の形式は "年/月/日 時:分" にしてください。', $e->getErrors()[4]);
$this->assertSame('7 行 : 日時の形式は "年/月/日 時:分" にしてください。', $e->getErrors()[5]);
$this->assertSame('8 行 : 日時の形式は "年/月/日 時:分" にしてください。', $e->getErrors()[6]);
$this->assertSame('9 行 : 日時の形式は "年/月/日 時:分" にしてください。', $e->getErrors()[7]);
$this->assertSame('10 行 : 日時の形式は "年/月/日 時:分" にしてください。', $e->getErrors()[8]);
$this->assertSame('11 行 : 日時の形式は "年/月/日 時:分" にしてください。', $e->getErrors()[9]);
$this->assertSame('12 行 : 日時の形式は "年/月/日 時:分" にしてください。', $e->getErrors()[10]);
$this->assertSame('13 行 : 日時の形式は "年/月/日 時:分" にしてください。', $e->getErrors()[11]);
$this->assertSame('14 行 : 日時の形式は "年/月/日 時:分" にしてください。', $e->getErrors()[12]);
$this->assertSame('15 行 : 日時の形式は "年/月/日 時:分" にしてください。', $e->getErrors()[13]);
$this->assertSame('16 行 : 日時の形式は "年/月/日 時:分" にしてください。', $e->getErrors()[14]);
$this->assertSame('17 行 : 日時の形式は "年/月/日 時:分" にしてください。', $e->getErrors()[15]);
return;
}
$this->fail('期待する例外が発生していません');
}
public function testNoteUTF8()
{
$user = factory(User::class)->create();
$importer = new CheckinCsvImporter($user, __DIR__ . '/../../fixture/Csv/note.utf8.csv');
$importer->execute();
$ejaculations = $user->ejaculations()->orderBy('ejaculated_date')->get();
$this->assertCount(3, $ejaculations);
$this->assertEquals('The quick brown fox jumps over the lazy dog. 素早い茶色の狐はのろまな犬を飛び越える', $ejaculations[0]->note);
$this->assertEquals("The quick brown fox jumps over the lazy dog.\n素早い茶色の狐はのろまな犬を飛び越える", $ejaculations[1]->note);
$this->assertEquals('The quick brown fox jumps over the "lazy" dog.', $ejaculations[2]->note);
}
/**
* @dataProvider provideNoteOverLength
*/
public function testNoteOverLength($filename)
{
$user = factory(User::class)->create();
$this->expectException(CsvImportException::class);
$this->expectExceptionMessage('2 行 : ートには500文字以下の文字列を指定してください。');
$importer = new CheckinCsvImporter($user, $filename);
$importer->execute();
}
public function provideNoteOverLength()
{
return [
'ASCII Only, UTF8' => [__DIR__ . '/../../fixture/Csv/note-over-length.ascii.utf8.csv'],
'JP, UTF8' => [__DIR__ . '/../../fixture/Csv/note-over-length.jp.utf8.csv'],
];
}
public function testLinkUTF8()
{
$user = factory(User::class)->create();
$importer = new CheckinCsvImporter($user, __DIR__ . '/../../fixture/Csv/link.utf8.csv');
$importer->execute();
$ejaculations = $user->ejaculations()->orderBy('ejaculated_date')->get();
$this->assertCount(1, $ejaculations);
$this->assertEquals('http://example.com', $ejaculations[0]->link);
}
public function testLinkOverLengthUTF8()
{
$user = factory(User::class)->create();
$this->expectException(CsvImportException::class);
$this->expectExceptionMessage('3 行 : オカズリンクには2000文字以下の文字列を指定してください。');
$importer = new CheckinCsvImporter($user, __DIR__ . '/../../fixture/Csv/link-over-length.utf8.csv');
$importer->execute();
}
public function testLinkIsNotUrlUTF8()
{
$user = factory(User::class)->create();
$this->expectException(CsvImportException::class);
$this->expectExceptionMessage('2 行 : オカズリンクには正しい形式のURLを指定してください。');
$importer = new CheckinCsvImporter($user, __DIR__ . '/../../fixture/Csv/link-not-url.utf8.csv');
$importer->execute();
}
public function testTag1UTF8()
{
$user = factory(User::class)->create();
$importer = new CheckinCsvImporter($user, __DIR__ . '/../../fixture/Csv/tag1.utf8.csv');
$importer->execute();
$ejaculation = $user->ejaculations()->first();
$tags = $ejaculation->tags()->get();
$this->assertSame(1, $user->ejaculations()->count());
$this->assertCount(1, $tags);
$this->assertEquals('貧乳', $tags[0]->name);
}
public function testTag2UTF8()
{
$user = factory(User::class)->create();
$importer = new CheckinCsvImporter($user, __DIR__ . '/../../fixture/Csv/tag2.utf8.csv');
$importer->execute();
$ejaculation = $user->ejaculations()->first();
$tags = $ejaculation->tags()->get();
$this->assertSame(1, $user->ejaculations()->count());
$this->assertCount(2, $tags);
$this->assertEquals('貧乳', $tags[0]->name);
$this->assertEquals('巨乳', $tags[1]->name);
}
public function testTagOverLengthUTF8()
{
$user = factory(User::class)->create();
$this->expectException(CsvImportException::class);
$this->expectExceptionMessage('3 行 : タグ1は255文字以内にしてください。');
$importer = new CheckinCsvImporter($user, __DIR__ . '/../../fixture/Csv/tag-over-length.utf8.csv');
$importer->execute();
}
public function testTagCanAcceptJumpedColumnUTF8()
{
$user = factory(User::class)->create();
$importer = new CheckinCsvImporter($user, __DIR__ . '/../../fixture/Csv/tag-jumped-column.utf8.csv');
$importer->execute();
$ejaculation = $user->ejaculations()->first();
$tags = $ejaculation->tags()->get();
$this->assertSame(1, $user->ejaculations()->count());
$this->assertCount(2, $tags);
$this->assertEquals('貧乳', $tags[0]->name);
$this->assertEquals('巨乳', $tags[1]->name);
}
public function testTagCantAcceptMultilineUTF8()
{
$user = factory(User::class)->create();
$this->expectException(CsvImportException::class);
$this->expectExceptionMessage('2 行 : タグ1に改行を含めることはできません。');
$importer = new CheckinCsvImporter($user, __DIR__ . '/../../fixture/Csv/tag-multiline.utf8.csv');
$importer->execute();
}
public function testTagCantAcceptWhitespaceUTF8()
{
$user = factory(User::class)->create();
$this->expectException(CsvImportException::class);
$this->expectExceptionMessage('2 行 : タグ1にスペースを含めることはできません。');
$importer = new CheckinCsvImporter($user, __DIR__ . '/../../fixture/Csv/tag-whitespace.utf8.csv');
$importer->execute();
}
public function testTagCanAccept32ColumnsUTF8()
{
$user = factory(User::class)->create();
$importer = new CheckinCsvImporter($user, __DIR__ . '/../../fixture/Csv/tag-33-column.utf8.csv');
$importer->execute();
$ejaculation = $user->ejaculations()->first();
$tags = $ejaculation->tags()->get();
$this->assertSame(1, $user->ejaculations()->count());
$this->assertCount(32, $tags);
$this->assertEquals('み', $tags[31]->name);
}
public function testSourceIsCsv()
{
$user = factory(User::class)->create();
$importer = new CheckinCsvImporter($user, __DIR__ . '/../../fixture/Csv/date.utf8.csv');
$importer->execute();
$ejaculation = $user->ejaculations()->first();
$this->assertSame(1, $user->ejaculations()->count());
$this->assertEquals(Ejaculation::SOURCE_CSV, $ejaculation->source);
}
public function testDontThrowUniqueKeyViolation()
{
$user = factory(User::class)->create();
factory(Ejaculation::class)->create([
'user_id' => $user->id,
'ejaculated_date' => Carbon::create(2020, 1, 23, 6, 1, 0, 'Asia/Tokyo')
]);
$this->expectException(CsvImportException::class);
$this->expectExceptionMessage('2 行 : すでにこの日時のチェックインデータが存在します。');
$importer = new CheckinCsvImporter($user, __DIR__ . '/../../fixture/Csv/date.utf8.csv');
$importer->execute();
}
public function testRecordLimit()
{
$user = factory(User::class)->create();
factory(Ejaculation::class, 5000)->create([
'user_id' => $user->id,
'source' => Ejaculation::SOURCE_CSV
]);
$this->expectException(CsvImportException::class);
$this->expectExceptionMessage('2 行 : インポート機能で取り込めるデータは5000件までに制限されています。これ以上取り込みできません。');
$importer = new CheckinCsvImporter($user, __DIR__ . '/../../fixture/Csv/link.utf8.csv');
$importer->execute();
}
}

2
tests/fixture/Csv/.editorconfig vendored Normal file
View File

@ -0,0 +1,2 @@
[*.csv]
end_of_line = crlf

View File

@ -0,0 +1,2 @@
日時
2020/01/23 06:01
1 日時
2 2020/01/23 06:01

View File

@ -0,0 +1,2 @@
日時
2020/1/23 6:01
1 日時
2 2020/1/23 6:01

View File

@ -0,0 +1,2 @@
日時
2020/1/23 6:01:02
1 日時
2 2020/1/23 6:01:02

2
tests/fixture/Csv/date.utf8.csv vendored Normal file
View File

@ -0,0 +1,2 @@
日時
2020/01/23 06:01:02
1 日時
2 2020/01/23 06:01:02

View File

@ -0,0 +1,2 @@
日時,ノート,オカズリンク
2019/1/01 0:01,テストテストあああああ,https://example.com/
1 日時 ノート オカズリンク
2 2019/1/01 0:01 テストテストあああああ https://example.com/

17
tests/fixture/Csv/invalid-date.utf8.csv vendored Normal file
View File

@ -0,0 +1,17 @@
日時,ノート
1999/12/31 23:59:59,最小境界
2100/01/01 00:00:00,最大境界
-1/01/01 00:00:00,存在しない日付
2019/-1/01 00:00:00,存在しない日付
2019/01/-1 00:00:00,存在しない日付
2019/02/29 00:00:00,存在しない日付
2019/00/01 00:00:00,存在しない日付
2019/01/00 00:00:00,存在しない日付
2019/01/32 00:00:00,存在しない日付
2019/13/01 00:00:00,存在しない日付
2019/01/01 00:60:00,存在しない時刻
2019/01/01 24:00:00,存在しない時刻
2019/01/01 00:00:60,存在しない時刻
2019/01/01 -1:00:00,存在しない時刻
2019/01/01 00:-1:00,存在しない時刻
2019/01/01 00:00:-1,存在しない時刻
1 日時 ノート
2 1999/12/31 23:59:59 最小境界
3 2100/01/01 00:00:00 最大境界
4 -1/01/01 00:00:00 存在しない日付
5 2019/-1/01 00:00:00 存在しない日付
6 2019/01/-1 00:00:00 存在しない日付
7 2019/02/29 00:00:00 存在しない日付
8 2019/00/01 00:00:00 存在しない日付
9 2019/01/00 00:00:00 存在しない日付
10 2019/01/32 00:00:00 存在しない日付
11 2019/13/01 00:00:00 存在しない日付
12 2019/01/01 00:60:00 存在しない時刻
13 2019/01/01 24:00:00 存在しない時刻
14 2019/01/01 00:00:60 存在しない時刻
15 2019/01/01 -1:00:00 存在しない時刻
16 2019/01/01 00:-1:00 存在しない時刻
17 2019/01/01 00:00:-1 存在しない時刻

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