SearchController.php 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  1. <?php
  2. namespace App\Http\Controllers;
  3. use Auth;
  4. use App\Hashtag;
  5. use App\Profile;
  6. use App\Status;
  7. use Illuminate\Http\Request;
  8. use App\Util\ActivityPub\Helpers;
  9. use Illuminate\Support\Facades\Cache;
  10. use Illuminate\Support\Str;
  11. use App\Transformer\Api\{
  12. AccountTransformer,
  13. HashtagTransformer,
  14. StatusTransformer,
  15. };
  16. use App\Services\WebfingerService;
  17. class SearchController extends Controller
  18. {
  19. public $tokens = [];
  20. public $term = '';
  21. public $hash = '';
  22. public $cacheKey = 'api:search:tag:';
  23. public function __construct()
  24. {
  25. $this->middleware('auth');
  26. }
  27. public function searchAPI(Request $request)
  28. {
  29. $this->validate($request, [
  30. 'q' => 'required|string|min:3|max:120',
  31. 'src' => 'required|string|in:metro',
  32. 'v' => 'required|integer|in:1',
  33. 'scope' => 'required|in:all,hashtag,profile,remote,webfinger'
  34. ]);
  35. $scope = $request->input('scope') ?? 'all';
  36. $this->term = e(urldecode($request->input('q')));
  37. $this->hash = hash('sha256', $this->term);
  38. switch ($scope) {
  39. case 'all':
  40. $this->getHashtags();
  41. $this->getPosts();
  42. $this->getProfiles();
  43. break;
  44. case 'hashtag':
  45. $this->getHashtags();
  46. break;
  47. case 'profile':
  48. $this->getProfiles();
  49. break;
  50. case 'webfinger':
  51. $this->webfingerSearch();
  52. break;
  53. default:
  54. break;
  55. }
  56. return response()->json($this->tokens, 200, [], JSON_PRETTY_PRINT);
  57. }
  58. protected function getPosts()
  59. {
  60. $tag = $this->term;
  61. $hash = hash('sha256', $tag);
  62. if( Helpers::validateUrl($tag) != false &&
  63. Helpers::validateLocalUrl($tag) != true &&
  64. config('federation.activitypub.enabled') == true &&
  65. config('federation.activitypub.remoteFollow') == true
  66. ) {
  67. $remote = Helpers::fetchFromUrl($tag);
  68. if( isset($remote['type']) &&
  69. $remote['type'] == 'Note') {
  70. $item = Helpers::statusFetch($tag);
  71. $this->tokens['posts'] = [[
  72. 'count' => 0,
  73. 'url' => $item->url(),
  74. 'type' => 'status',
  75. 'value' => "by {$item->profile->username} <span class='float-right'>{$item->created_at->diffForHumans(null, true, true)}</span>",
  76. 'tokens' => [$item->caption],
  77. 'name' => $item->caption,
  78. 'thumb' => $item->thumb(),
  79. ]];
  80. }
  81. } else {
  82. $posts = Status::select('id', 'profile_id', 'caption', 'created_at')
  83. ->whereHas('media')
  84. ->whereNull('in_reply_to_id')
  85. ->whereNull('reblog_of_id')
  86. ->whereProfileId(Auth::user()->profile_id)
  87. ->where('caption', 'like', '%'.$tag.'%')
  88. ->latest()
  89. ->limit(10)
  90. ->get();
  91. if($posts->count() > 0) {
  92. $posts = $posts->map(function($item, $key) {
  93. return [
  94. 'count' => 0,
  95. 'url' => $item->url(),
  96. 'type' => 'status',
  97. 'value' => "by {$item->profile->username} <span class='float-right'>{$item->created_at->diffForHumans(null, true, true)}</span>",
  98. 'tokens' => [$item->caption],
  99. 'name' => $item->caption,
  100. 'thumb' => $item->thumb(),
  101. 'filter' => $item->firstMedia()->filter_class
  102. ];
  103. });
  104. $this->tokens['posts'] = $posts;
  105. }
  106. }
  107. }
  108. protected function getHashtags()
  109. {
  110. $tag = $this->term;
  111. $key = $this->cacheKey . 'hashtags:' . $this->hash;
  112. $ttl = now()->addMinutes(1);
  113. $tokens = Cache::remember($key, $ttl, function() use($tag) {
  114. $htag = Str::startsWith($tag, '#') == true ? mb_substr($tag, 1) : $tag;
  115. $hashtags = Hashtag::select('id', 'name', 'slug')
  116. ->where('slug', 'like', '%'.$htag.'%')
  117. ->whereHas('posts')
  118. ->limit(20)
  119. ->get();
  120. if($hashtags->count() > 0) {
  121. $tags = $hashtags->map(function ($item, $key) {
  122. return [
  123. 'count' => $item->posts()->count(),
  124. 'url' => $item->url(),
  125. 'type' => 'hashtag',
  126. 'value' => $item->name,
  127. 'tokens' => '',
  128. 'name' => null,
  129. ];
  130. });
  131. return $tags;
  132. }
  133. });
  134. $this->tokens['hashtags'] = $tokens;
  135. }
  136. protected function getProfiles()
  137. {
  138. $tag = $this->term;
  139. $remoteKey = $this->cacheKey . 'profiles:remote:' . $this->hash;
  140. $key = $this->cacheKey . 'profiles:' . $this->hash;
  141. $remoteTtl = now()->addMinutes(15);
  142. $ttl = now()->addHours(2);
  143. if( Helpers::validateUrl($tag) != false &&
  144. Helpers::validateLocalUrl($tag) != true &&
  145. config('federation.activitypub.enabled') == true &&
  146. config('federation.activitypub.remoteFollow') == true
  147. ) {
  148. $remote = Helpers::fetchFromUrl($tag);
  149. if( isset($remote['type']) &&
  150. $remote['type'] == 'Person'
  151. ) {
  152. $this->tokens['profiles'] = Cache::remember($remoteKey, $remoteTtl, function() use($tag) {
  153. $item = Helpers::profileFirstOrNew($tag);
  154. $tokens = [[
  155. 'count' => 1,
  156. 'url' => $item->url(),
  157. 'type' => 'profile',
  158. 'value' => $item->username,
  159. 'tokens' => [$item->username],
  160. 'name' => $item->name,
  161. 'entity' => [
  162. 'id' => (string) $item->id,
  163. 'following' => $item->followedBy(Auth::user()->profile),
  164. 'follow_request' => $item->hasFollowRequestById(Auth::user()->profile_id),
  165. 'thumb' => $item->avatarUrl(),
  166. 'local' => (bool) !$item->domain
  167. ]
  168. ]];
  169. return $tokens;
  170. });
  171. }
  172. }
  173. // elseif( Str::containsAll($tag, ['@', '.'])
  174. // config('federation.activitypub.enabled') == true &&
  175. // config('federation.activitypub.remoteFollow') == true
  176. // ) {
  177. // if(substr_count($tag, '@') == 2) {
  178. // $domain = last(explode('@', sub_str($u, 1)));
  179. // } else {
  180. // $domain = last(explode('@', $u));
  181. // }
  182. // }
  183. else {
  184. $this->tokens['profiles'] = Cache::remember($key, $ttl, function() use($tag) {
  185. $users = Profile::select('domain', 'username', 'name', 'id')
  186. ->whereNull('status')
  187. ->where('id', '!=', Auth::user()->profile->id)
  188. ->where('username', 'like', '%'.$tag.'%')
  189. ->limit(20)
  190. ->get();
  191. if($users->count() > 0) {
  192. return $users->map(function ($item, $key) {
  193. return [
  194. 'count' => 0,
  195. 'url' => $item->url(),
  196. 'type' => 'profile',
  197. 'value' => $item->username,
  198. 'tokens' => [$item->username],
  199. 'name' => $item->name,
  200. 'avatar' => $item->avatarUrl(),
  201. 'id' => (string) $item->id,
  202. 'entity' => [
  203. 'id' => (string) $item->id,
  204. 'following' => $item->followedBy(Auth::user()->profile),
  205. 'follow_request' => $item->hasFollowRequestById(Auth::user()->profile_id),
  206. 'thumb' => $item->avatarUrl(),
  207. 'local' => (bool) !$item->domain,
  208. 'post_count' => $item->statuses()->count()
  209. ]
  210. ];
  211. });
  212. }
  213. });
  214. }
  215. }
  216. public function results(Request $request)
  217. {
  218. $this->validate($request, [
  219. 'q' => 'required|string|min:1',
  220. ]);
  221. return view('search.results');
  222. }
  223. protected function webfingerSearch()
  224. {
  225. $wfs = WebfingerService::lookup($this->term);
  226. if(empty($wfs)) {
  227. return;
  228. }
  229. $this->tokens['profiles'] = [
  230. [
  231. 'count' => 1,
  232. 'url' => $wfs['url'],
  233. 'type' => 'profile',
  234. 'value' => $wfs['username'],
  235. 'tokens' => [$wfs['username']],
  236. 'name' => $wfs['display_name'],
  237. 'entity' => [
  238. 'id' => (string) $wfs['id'],
  239. 'following' => null,
  240. 'follow_request' => null,
  241. 'thumb' => $wfs['avatar'],
  242. 'local' => (bool) $wfs['local']
  243. ]
  244. ]
  245. ];
  246. return;
  247. }
  248. }