pixelfed/app/Http/Controllers/SearchController.php

92 lines
3.1 KiB
PHP
Raw Normal View History

2018-05-26 22:50:36 +00:00
<?php
namespace App\Http\Controllers;
2018-09-27 05:00:45 +00:00
use Auth;
2018-08-28 03:07:36 +00:00
use App\Hashtag;
use App\Profile;
2018-09-27 05:00:45 +00:00
use App\Status;
2018-05-26 22:50:36 +00:00
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
class SearchController extends Controller
{
2018-09-27 05:00:45 +00:00
public function __construct()
{
$this->middleware('auth');
}
2018-05-26 22:50:36 +00:00
public function searchAPI(Request $request, $tag)
{
2018-09-27 05:00:45 +00:00
if(mb_strlen($tag) < 3) {
return;
}
$hash = hash('sha256', $tag);
2018-12-24 05:07:19 +00:00
$tokens = Cache::remember('api:search:tag:'.$hash, 5, function () use ($tag) {
2018-09-27 05:00:45 +00:00
$tokens = collect([]);
$hashtags = Hashtag::select('id', 'name', 'slug')->where('slug', 'like', '%'.$tag.'%')->limit(20)->get();
if($hashtags->count() > 0) {
$tags = $hashtags->map(function ($item, $key) {
return [
'count' => $item->posts()->count(),
'url' => $item->url(),
'type' => 'hashtag',
'value' => $item->name,
'tokens' => explode('-', $item->name),
'name' => null,
];
});
$tokens->push($tags);
}
2018-11-19 03:42:35 +00:00
$users = Profile::select('username', 'name', 'id')
2018-12-24 05:07:19 +00:00
->whereNull('status')
2018-11-19 03:42:35 +00:00
->where('username', 'like', '%'.$tag.'%')
->limit(20)
->get();
2018-09-27 05:00:45 +00:00
if($users->count() > 0) {
$profiles = $users->map(function ($item, $key) {
return [
'count' => 0,
'url' => $item->url(),
'type' => 'profile',
'value' => $item->username,
'tokens' => [$item->username],
'name' => $item->name,
];
});
$tokens->push($profiles);
}
2018-08-28 03:07:36 +00:00
2018-09-27 05:00:45 +00:00
return $tokens;
2018-05-26 22:50:36 +00:00
});
2018-09-27 05:00:45 +00:00
$posts = Status::select('id', 'profile_id', 'caption', 'created_at')
->whereHas('media')
->whereNull('in_reply_to_id')
->whereNull('reblog_of_id')
->whereProfileId(Auth::user()->profile->id)
->where('caption', 'like', '%'.$tag.'%')
->orderBy('created_at', 'desc')
->get();
2018-05-26 22:50:36 +00:00
2018-09-27 05:00:45 +00:00
if($posts->count() > 0) {
$posts = $posts->map(function($item, $key) {
return [
'count' => 0,
'url' => $item->url(),
'type' => 'status',
2018-11-19 03:42:35 +00:00
'value' => "by {$item->profile->username} <span class='float-right'>{$item->created_at->diffForHumans(null, true, true)}</span>",
2018-09-27 05:00:45 +00:00
'tokens' => [$item->caption],
'name' => $item->caption,
'thumb' => $item->thumb(),
];
});
$tokens = $tokens->push($posts);
}
if($tokens->count() > 0) {
$tokens = $tokens[0];
}
return response()->json($tokens);
2018-05-26 22:50:36 +00:00
}
}