SearchController.php 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  1. <?php
  2. namespace App\Http\Controllers;
  3. use Auth;
  4. use App\Hashtag;
  5. use App\Place;
  6. use App\Profile;
  7. use App\Status;
  8. use Illuminate\Http\Request;
  9. use App\Util\ActivityPub\Helpers;
  10. use Illuminate\Support\Facades\Cache;
  11. use Illuminate\Support\Str;
  12. use App\Transformer\Api\{
  13. AccountTransformer,
  14. HashtagTransformer,
  15. StatusTransformer,
  16. };
  17. use App\Services\WebfingerService;
  18. class SearchController extends Controller
  19. {
  20. public $tokens = [];
  21. public $term = '';
  22. public $hash = '';
  23. public $cacheKey = 'api:search:tag:';
  24. public function __construct()
  25. {
  26. $this->middleware('auth');
  27. }
  28. public function searchAPI(Request $request)
  29. {
  30. $this->validate($request, [
  31. 'q' => 'required|string|min:3|max:120',
  32. 'src' => 'required|string|in:metro',
  33. 'v' => 'required|integer|in:2',
  34. 'scope' => 'required|in:all,hashtag,profile,remote,webfinger'
  35. ]);
  36. $scope = $request->input('scope') ?? 'all';
  37. $this->term = e(urldecode($request->input('q')));
  38. $this->hash = hash('sha256', $this->term);
  39. switch ($scope) {
  40. case 'all':
  41. $this->getHashtags();
  42. $this->getPosts();
  43. $this->getProfiles();
  44. // $this->getPlaces();
  45. break;
  46. case 'hashtag':
  47. $this->getHashtags();
  48. break;
  49. case 'profile':
  50. $this->getProfiles();
  51. break;
  52. case 'webfinger':
  53. $this->webfingerSearch();
  54. break;
  55. case 'remote':
  56. $this->remoteLookupSearch();
  57. break;
  58. case 'place':
  59. $this->getPlaces();
  60. break;
  61. default:
  62. break;
  63. }
  64. return response()->json($this->tokens, 200, [], JSON_PRETTY_PRINT);
  65. }
  66. protected function getPosts()
  67. {
  68. $tag = $this->term;
  69. $hash = hash('sha256', $tag);
  70. if( Helpers::validateUrl($tag) != false &&
  71. Helpers::validateLocalUrl($tag) != true &&
  72. config_cache('federation.activitypub.enabled') == true &&
  73. config('federation.activitypub.remoteFollow') == true
  74. ) {
  75. $remote = Helpers::fetchFromUrl($tag);
  76. if( isset($remote['type']) &&
  77. $remote['type'] == 'Note') {
  78. $item = Helpers::statusFetch($tag);
  79. $this->tokens['posts'] = [[
  80. 'count' => 0,
  81. 'url' => $item->url(),
  82. 'type' => 'status',
  83. 'value' => "by {$item->profile->username} <span class='float-right'>{$item->created_at->diffForHumans(null, true, true)}</span>",
  84. 'tokens' => [$item->caption],
  85. 'name' => $item->caption,
  86. 'thumb' => $item->thumb(),
  87. ]];
  88. }
  89. } else {
  90. $posts = Status::select('id', 'profile_id', 'caption', 'created_at')
  91. ->whereHas('media')
  92. ->whereNull('in_reply_to_id')
  93. ->whereNull('reblog_of_id')
  94. ->whereProfileId(Auth::user()->profile_id)
  95. ->where('caption', 'like', '%'.$tag.'%')
  96. ->latest()
  97. ->limit(10)
  98. ->get();
  99. if($posts->count() > 0) {
  100. $posts = $posts->map(function($item, $key) {
  101. return [
  102. 'count' => 0,
  103. 'url' => $item->url(),
  104. 'type' => 'status',
  105. 'value' => "by {$item->profile->username} <span class='float-right'>{$item->created_at->diffForHumans(null, true, true)}</span>",
  106. 'tokens' => [$item->caption],
  107. 'name' => $item->caption,
  108. 'thumb' => $item->thumb(),
  109. 'filter' => $item->firstMedia()->filter_class
  110. ];
  111. });
  112. $this->tokens['posts'] = $posts;
  113. }
  114. }
  115. }
  116. protected function getHashtags()
  117. {
  118. $tag = $this->term;
  119. $key = $this->cacheKey . 'hashtags:' . $this->hash;
  120. $ttl = now()->addMinutes(1);
  121. $tokens = Cache::remember($key, $ttl, function() use($tag) {
  122. $htag = Str::startsWith($tag, '#') == true ? mb_substr($tag, 1) : $tag;
  123. $hashtags = Hashtag::select('id', 'name', 'slug')
  124. ->where('slug', 'like', '%'.$htag.'%')
  125. ->whereHas('posts')
  126. ->limit(20)
  127. ->get();
  128. if($hashtags->count() > 0) {
  129. $tags = $hashtags->map(function ($item, $key) {
  130. return [
  131. 'count' => $item->posts()->count(),
  132. 'url' => $item->url(),
  133. 'type' => 'hashtag',
  134. 'value' => $item->name,
  135. 'tokens' => '',
  136. 'name' => null,
  137. ];
  138. });
  139. return $tags;
  140. }
  141. });
  142. $this->tokens['hashtags'] = $tokens;
  143. }
  144. protected function getPlaces()
  145. {
  146. $tag = $this->term;
  147. // $key = $this->cacheKey . 'places:' . $this->hash;
  148. // $ttl = now()->addHours(12);
  149. // $tokens = Cache::remember($key, $ttl, function() use($tag) {
  150. $htag = Str::contains($tag, ',') == true ? explode(',', $tag) : [$tag];
  151. $hashtags = Place::select('id', 'name', 'slug', 'country')
  152. ->where('name', 'like', '%'.$htag[0].'%')
  153. ->paginate(20);
  154. $tags = [];
  155. if($hashtags->count() > 0) {
  156. $tags = $hashtags->map(function ($item, $key) {
  157. return [
  158. 'count' => null,
  159. 'url' => $item->url(),
  160. 'type' => 'place',
  161. 'value' => $item->name . ', ' . $item->country,
  162. 'tokens' => '',
  163. 'name' => null,
  164. 'city' => $item->name,
  165. 'country' => $item->country
  166. ];
  167. });
  168. // return $tags;
  169. }
  170. // });
  171. $this->tokens['places'] = $tags;
  172. $this->tokens['placesPagination'] = [
  173. 'total' => $hashtags->total(),
  174. 'current_page' => $hashtags->currentPage(),
  175. 'last_page' => $hashtags->lastPage()
  176. ];
  177. }
  178. protected function getProfiles()
  179. {
  180. $tag = $this->term;
  181. $remoteKey = $this->cacheKey . 'profiles:remote:' . $this->hash;
  182. $key = $this->cacheKey . 'profiles:' . $this->hash;
  183. $remoteTtl = now()->addMinutes(15);
  184. $ttl = now()->addHours(2);
  185. if( Helpers::validateUrl($tag) != false &&
  186. Helpers::validateLocalUrl($tag) != true &&
  187. config_cache('federation.activitypub.enabled') == true &&
  188. config('federation.activitypub.remoteFollow') == true
  189. ) {
  190. $remote = Helpers::fetchFromUrl($tag);
  191. if( isset($remote['type']) &&
  192. $remote['type'] == 'Person'
  193. ) {
  194. $this->tokens['profiles'] = Cache::remember($remoteKey, $remoteTtl, function() use($tag) {
  195. $item = Helpers::profileFirstOrNew($tag);
  196. $tokens = [[
  197. 'count' => 1,
  198. 'url' => $item->url(),
  199. 'type' => 'profile',
  200. 'value' => $item->username,
  201. 'tokens' => [$item->username],
  202. 'name' => $item->name,
  203. 'entity' => [
  204. 'id' => (string) $item->id,
  205. 'following' => $item->followedBy(Auth::user()->profile),
  206. 'follow_request' => $item->hasFollowRequestById(Auth::user()->profile_id),
  207. 'thumb' => $item->avatarUrl(),
  208. 'local' => (bool) !$item->domain,
  209. 'post_count' => $item->statuses()->count()
  210. ]
  211. ]];
  212. return $tokens;
  213. });
  214. }
  215. }
  216. else {
  217. $this->tokens['profiles'] = Cache::remember($key, $ttl, function() use($tag) {
  218. if(Str::startsWith($tag, '@')) {
  219. $tag = substr($tag, 1);
  220. }
  221. $users = Profile::select('status', 'domain', 'username', 'name', 'id')
  222. ->whereNull('status')
  223. ->where('username', 'like', '%'.$tag.'%')
  224. ->limit(20)
  225. ->orderBy('domain')
  226. ->get();
  227. if($users->count() > 0) {
  228. return $users->map(function ($item, $key) {
  229. return [
  230. 'count' => 0,
  231. 'url' => $item->url(),
  232. 'type' => 'profile',
  233. 'value' => $item->username,
  234. 'tokens' => [$item->username],
  235. 'name' => $item->name,
  236. 'avatar' => $item->avatarUrl(),
  237. 'id' => (string) $item->id,
  238. 'entity' => [
  239. 'id' => (string) $item->id,
  240. 'following' => $item->followedBy(Auth::user()->profile),
  241. 'follow_request' => $item->hasFollowRequestById(Auth::user()->profile_id),
  242. 'thumb' => $item->avatarUrl(),
  243. 'local' => (bool) !$item->domain,
  244. 'post_count' => $item->statuses()->count()
  245. ]
  246. ];
  247. });
  248. }
  249. });
  250. }
  251. }
  252. public function results(Request $request)
  253. {
  254. $this->validate($request, [
  255. 'q' => 'required|string|min:1',
  256. ]);
  257. return view('search.results');
  258. }
  259. protected function webfingerSearch()
  260. {
  261. $wfs = WebfingerService::lookup($this->term);
  262. if(empty($wfs)) {
  263. return;
  264. }
  265. $this->tokens['profiles'] = [
  266. [
  267. 'count' => 1,
  268. 'url' => $wfs['url'],
  269. 'type' => 'profile',
  270. 'value' => $wfs['username'],
  271. 'tokens' => [$wfs['username']],
  272. 'name' => $wfs['display_name'],
  273. 'entity' => [
  274. 'id' => (string) $wfs['id'],
  275. 'following' => null,
  276. 'follow_request' => null,
  277. 'thumb' => $wfs['avatar'],
  278. 'local' => (bool) $wfs['local']
  279. ]
  280. ]
  281. ];
  282. return;
  283. }
  284. protected function remotePostLookup()
  285. {
  286. $tag = $this->term;
  287. $hash = hash('sha256', $tag);
  288. $local = Helpers::validateLocalUrl($tag);
  289. $valid = Helpers::validateUrl($tag);
  290. if($valid == false || $local == true) {
  291. return;
  292. }
  293. if(Status::whereUri($tag)->whereLocal(false)->exists()) {
  294. $item = Status::whereUri($tag)->first();
  295. $media = $item->firstMedia();
  296. $url = null;
  297. if($media) {
  298. $url = $media->remote_url;
  299. }
  300. $this->tokens['posts'] = [[
  301. 'count' => 0,
  302. 'url' => "/i/web/post/_/$item->profile_id/$item->id",
  303. 'type' => 'status',
  304. 'username' => $item->profile->username,
  305. 'caption' => $item->rendered ?? $item->caption,
  306. 'thumb' => $url,
  307. 'timestamp' => $item->created_at->diffForHumans()
  308. ]];
  309. }
  310. $remote = Helpers::fetchFromUrl($tag);
  311. if(isset($remote['type']) && $remote['type'] == 'Note') {
  312. $item = Helpers::statusFetch($tag);
  313. $media = $item->firstMedia();
  314. $url = null;
  315. if($media) {
  316. $url = $media->remote_url;
  317. }
  318. $this->tokens['posts'] = [[
  319. 'count' => 0,
  320. 'url' => "/i/web/post/_/$item->profile_id/$item->id",
  321. 'type' => 'status',
  322. 'username' => $item->profile->username,
  323. 'caption' => $item->rendered ?? $item->caption,
  324. 'thumb' => $url,
  325. 'timestamp' => $item->created_at->diffForHumans()
  326. ]];
  327. }
  328. }
  329. protected function remoteLookupSearch()
  330. {
  331. if(!Helpers::validateUrl($this->term)) {
  332. return;
  333. }
  334. $this->getProfiles();
  335. $this->remotePostLookup();
  336. }
  337. }