DirectMessageController.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664
  1. <?php
  2. namespace App\Http\Controllers;
  3. use Auth, Cache;
  4. use Illuminate\Http\Request;
  5. use App\{
  6. DirectMessage,
  7. Media,
  8. Notification,
  9. Profile,
  10. Status,
  11. User,
  12. UserFilter,
  13. UserSetting
  14. };
  15. use App\Services\MediaPathService;
  16. use App\Services\MediaBlocklistService;
  17. use App\Jobs\StatusPipeline\NewStatusPipeline;
  18. use Illuminate\Support\Str;
  19. use App\Util\ActivityPub\Helpers;
  20. use App\Services\WebfingerService;
  21. class DirectMessageController extends Controller
  22. {
  23. public function __construct()
  24. {
  25. $this->middleware('auth');
  26. }
  27. public function browse(Request $request)
  28. {
  29. $this->validate($request, [
  30. 'a' => 'nullable|string|in:inbox,sent,filtered',
  31. 'page' => 'nullable|integer|min:1|max:99'
  32. ]);
  33. $profile = $request->user()->profile_id;
  34. $action = $request->input('a', 'inbox');
  35. $page = $request->input('page');
  36. if($action == 'inbox') {
  37. $dms = DirectMessage::selectRaw('*, max(created_at) as createdAt')
  38. ->whereToId($profile)
  39. ->with(['author','status'])
  40. ->whereIsHidden(false)
  41. ->groupBy('from_id')
  42. ->latest()
  43. ->when($page, function($q, $page) {
  44. if($page > 1) {
  45. return $q->offset($page * 8 - 8);
  46. }
  47. })
  48. ->limit(8)
  49. ->get()
  50. ->map(function($r) use($profile) {
  51. return $r->from_id !== $profile ? [
  52. 'id' => (string) $r->from_id,
  53. 'name' => $r->author->name,
  54. 'username' => $r->author->username,
  55. 'avatar' => $r->author->avatarUrl(),
  56. 'url' => $r->author->url(),
  57. 'isLocal' => (bool) !$r->author->domain,
  58. 'domain' => $r->author->domain,
  59. 'timeAgo' => $r->created_at->diffForHumans(null, true, true),
  60. 'lastMessage' => $r->status->caption,
  61. 'messages' => []
  62. ] : [
  63. 'id' => (string) $r->to_id,
  64. 'name' => $r->recipient->name,
  65. 'username' => $r->recipient->username,
  66. 'avatar' => $r->recipient->avatarUrl(),
  67. 'url' => $r->recipient->url(),
  68. 'isLocal' => (bool) !$r->recipient->domain,
  69. 'domain' => $r->recipient->domain,
  70. 'timeAgo' => $r->created_at->diffForHumans(null, true, true),
  71. 'lastMessage' => $r->status->caption,
  72. 'messages' => []
  73. ];
  74. });
  75. }
  76. if($action == 'sent') {
  77. $dms = DirectMessage::selectRaw('*, max(created_at) as createdAt')
  78. ->whereFromId($profile)
  79. ->with(['author','status'])
  80. ->groupBy('to_id')
  81. ->orderBy('createdAt', 'desc')
  82. ->when($page, function($q, $page) {
  83. if($page > 1) {
  84. return $q->offset($page * 8 - 8);
  85. }
  86. })
  87. ->limit(8)
  88. ->get()
  89. ->map(function($r) use($profile) {
  90. return $r->from_id !== $profile ? [
  91. 'id' => (string) $r->from_id,
  92. 'name' => $r->author->name,
  93. 'username' => $r->author->username,
  94. 'avatar' => $r->author->avatarUrl(),
  95. 'url' => $r->author->url(),
  96. 'isLocal' => (bool) !$r->author->domain,
  97. 'domain' => $r->author->domain,
  98. 'timeAgo' => $r->created_at->diffForHumans(null, true, true),
  99. 'lastMessage' => $r->status->caption,
  100. 'messages' => []
  101. ] : [
  102. 'id' => (string) $r->to_id,
  103. 'name' => $r->recipient->name,
  104. 'username' => $r->recipient->username,
  105. 'avatar' => $r->recipient->avatarUrl(),
  106. 'url' => $r->recipient->url(),
  107. 'isLocal' => (bool) !$r->recipient->domain,
  108. 'domain' => $r->recipient->domain,
  109. 'timeAgo' => $r->created_at->diffForHumans(null, true, true),
  110. 'lastMessage' => $r->status->caption,
  111. 'messages' => []
  112. ];
  113. });
  114. }
  115. if($action == 'filtered') {
  116. $dms = DirectMessage::selectRaw('*, max(created_at) as createdAt')
  117. ->whereToId($profile)
  118. ->with(['author','status'])
  119. ->whereIsHidden(true)
  120. ->groupBy('from_id')
  121. ->orderBy('createdAt', 'desc')
  122. ->when($page, function($q, $page) {
  123. if($page > 1) {
  124. return $q->offset($page * 8 - 8);
  125. }
  126. })
  127. ->limit(8)
  128. ->get()
  129. ->map(function($r) use($profile) {
  130. return $r->from_id !== $profile ? [
  131. 'id' => (string) $r->from_id,
  132. 'name' => $r->author->name,
  133. 'username' => $r->author->username,
  134. 'avatar' => $r->author->avatarUrl(),
  135. 'url' => $r->author->url(),
  136. 'isLocal' => (bool) !$r->author->domain,
  137. 'domain' => $r->author->domain,
  138. 'timeAgo' => $r->created_at->diffForHumans(null, true, true),
  139. 'lastMessage' => $r->status->caption,
  140. 'messages' => []
  141. ] : [
  142. 'id' => (string) $r->to_id,
  143. 'name' => $r->recipient->name,
  144. 'username' => $r->recipient->username,
  145. 'avatar' => $r->recipient->avatarUrl(),
  146. 'url' => $r->recipient->url(),
  147. 'isLocal' => (bool) !$r->recipient->domain,
  148. 'domain' => $r->recipient->domain,
  149. 'timeAgo' => $r->created_at->diffForHumans(null, true, true),
  150. 'lastMessage' => $r->status->caption,
  151. 'messages' => []
  152. ];
  153. });
  154. }
  155. return response()->json($dms);
  156. }
  157. public function create(Request $request)
  158. {
  159. $this->validate($request, [
  160. 'to_id' => 'required',
  161. 'message' => 'required|string|min:1|max:500',
  162. 'type' => 'required|in:text,emoji'
  163. ]);
  164. $profile = $request->user()->profile;
  165. $recipient = Profile::where('id', '!=', $profile->id)->findOrFail($request->input('to_id'));
  166. abort_if(in_array($profile->id, $recipient->blockedIds()->toArray()), 403);
  167. $msg = $request->input('message');
  168. if((!$recipient->domain && $recipient->user->settings->public_dm == false) || $recipient->is_private) {
  169. if($recipient->follows($profile) == true) {
  170. $hidden = false;
  171. } else {
  172. $hidden = true;
  173. }
  174. } else {
  175. $hidden = false;
  176. }
  177. $status = new Status;
  178. $status->profile_id = $profile->id;
  179. $status->caption = $msg;
  180. $status->rendered = $msg;
  181. $status->visibility = 'direct';
  182. $status->scope = 'direct';
  183. $status->in_reply_to_profile_id = $recipient->id;
  184. $status->save();
  185. $dm = new DirectMessage;
  186. $dm->to_id = $recipient->id;
  187. $dm->from_id = $profile->id;
  188. $dm->status_id = $status->id;
  189. $dm->is_hidden = $hidden;
  190. $dm->type = $request->input('type');
  191. $dm->save();
  192. if(filter_var($msg, FILTER_VALIDATE_URL)) {
  193. if(Helpers::validateUrl($msg)) {
  194. $dm->type = 'link';
  195. $dm->meta = [
  196. 'domain' => parse_url($msg, PHP_URL_HOST),
  197. 'local' => parse_url($msg, PHP_URL_HOST) ==
  198. parse_url(config('app.url'), PHP_URL_HOST)
  199. ];
  200. $dm->save();
  201. }
  202. }
  203. $nf = UserFilter::whereUserId($recipient->id)
  204. ->whereFilterableId($profile->id)
  205. ->whereFilterableType('App\Profile')
  206. ->whereFilterType('dm.mute')
  207. ->exists();
  208. if($recipient->domain == null && $hidden == false && !$nf) {
  209. $notification = new Notification();
  210. $notification->profile_id = $recipient->id;
  211. $notification->actor_id = $profile->id;
  212. $notification->action = 'dm';
  213. $notification->message = $dm->toText();
  214. $notification->rendered = $dm->toHtml();
  215. $notification->item_id = $dm->id;
  216. $notification->item_type = "App\DirectMessage";
  217. $notification->save();
  218. }
  219. if($recipient->domain) {
  220. $this->remoteDeliver($dm);
  221. }
  222. $res = [
  223. 'id' => (string) $dm->id,
  224. 'isAuthor' => $profile->id == $dm->from_id,
  225. 'reportId' => (string) $dm->status_id,
  226. 'hidden' => (bool) $dm->is_hidden,
  227. 'type' => $dm->type,
  228. 'text' => $dm->status->caption,
  229. 'media' => null,
  230. 'timeAgo' => $dm->created_at->diffForHumans(null,null,true),
  231. 'seen' => $dm->read_at != null,
  232. 'meta' => $dm->meta
  233. ];
  234. return response()->json($res);
  235. }
  236. public function thread(Request $request)
  237. {
  238. $this->validate($request, [
  239. 'pid' => 'required'
  240. ]);
  241. $uid = $request->user()->profile_id;
  242. $pid = $request->input('pid');
  243. $max_id = $request->input('max_id');
  244. $min_id = $request->input('min_id');
  245. $r = Profile::findOrFail($pid);
  246. // $r = Profile::whereNull('domain')->findOrFail($pid);
  247. if($min_id) {
  248. $res = DirectMessage::select('*')
  249. ->where('id', '>', $min_id)
  250. ->where(function($q) use($pid,$uid) {
  251. return $q->where([['from_id',$pid],['to_id',$uid]
  252. ])->orWhere([['from_id',$uid],['to_id',$pid]]);
  253. })
  254. ->latest()
  255. ->take(8)
  256. ->get();
  257. } else if ($max_id) {
  258. $res = DirectMessage::select('*')
  259. ->where('id', '<', $max_id)
  260. ->where(function($q) use($pid,$uid) {
  261. return $q->where([['from_id',$pid],['to_id',$uid]
  262. ])->orWhere([['from_id',$uid],['to_id',$pid]]);
  263. })
  264. ->latest()
  265. ->take(8)
  266. ->get();
  267. } else {
  268. $res = DirectMessage::where(function($q) use($pid,$uid) {
  269. return $q->where([['from_id',$pid],['to_id',$uid]
  270. ])->orWhere([['from_id',$uid],['to_id',$pid]]);
  271. })
  272. ->latest()
  273. ->take(8)
  274. ->get();
  275. }
  276. $res = $res->map(function($s) use ($uid){
  277. return [
  278. 'id' => (string) $s->id,
  279. 'hidden' => (bool) $s->is_hidden,
  280. 'isAuthor' => $uid == $s->from_id,
  281. 'type' => $s->type,
  282. 'text' => $s->status->caption,
  283. 'media' => $s->status->firstMedia() ? $s->status->firstMedia()->url() : null,
  284. 'timeAgo' => $s->created_at->diffForHumans(null,null,true),
  285. 'seen' => $s->read_at != null,
  286. 'reportId' => (string) $s->status_id,
  287. 'meta' => json_decode($s->meta,true)
  288. ];
  289. });
  290. $w = [
  291. 'id' => (string) $r->id,
  292. 'name' => $r->name,
  293. 'username' => $r->username,
  294. 'avatar' => $r->avatarUrl(),
  295. 'url' => $r->url(),
  296. 'muted' => UserFilter::whereUserId($uid)
  297. ->whereFilterableId($r->id)
  298. ->whereFilterableType('App\Profile')
  299. ->whereFilterType('dm.mute')
  300. ->first() ? true : false,
  301. 'isLocal' => (bool) !$r->domain,
  302. 'domain' => $r->domain,
  303. 'timeAgo' => $r->created_at->diffForHumans(null, true, true),
  304. 'lastMessage' => '',
  305. 'messages' => $res
  306. ];
  307. return response()->json($w, 200, [], JSON_PRETTY_PRINT|JSON_UNESCAPED_SLASHES);
  308. }
  309. public function delete(Request $request)
  310. {
  311. $this->validate($request, [
  312. 'id' => 'required'
  313. ]);
  314. $sid = $request->input('id');
  315. $pid = $request->user()->profile_id;
  316. $dm = DirectMessage::whereFromId($pid)
  317. ->whereStatusId($sid)
  318. ->firstOrFail();
  319. $status = Status::whereProfileId($pid)
  320. ->findOrFail($dm->status_id);
  321. if($dm->recipient->domain) {
  322. $dmc = $dm;
  323. $this->remoteDelete($dmc);
  324. }
  325. $status->delete();
  326. $dm->delete();
  327. return [200];
  328. }
  329. public function get(Request $request, $id)
  330. {
  331. $pid = $request->user()->profile_id;
  332. $dm = DirectMessage::whereStatusId($id)->firstOrFail();
  333. abort_if($pid !== $dm->to_id && $pid !== $dm->from_id, 404);
  334. return response()->json($dm, 200, [], JSON_PRETTY_PRINT|JSON_UNESCAPED_SLASHES);
  335. }
  336. public function mediaUpload(Request $request)
  337. {
  338. $this->validate($request, [
  339. 'file' => function() {
  340. return [
  341. 'required',
  342. 'mimes:' . config('pixelfed.media_types'),
  343. 'max:' . config('pixelfed.max_photo_size'),
  344. ];
  345. },
  346. 'to_id' => 'required'
  347. ]);
  348. $user = $request->user();
  349. $profile = $user->profile;
  350. $recipient = Profile::where('id', '!=', $profile->id)->findOrFail($request->input('to_id'));
  351. abort_if(in_array($profile->id, $recipient->blockedIds()->toArray()), 403);
  352. if((!$recipient->domain && $recipient->user->settings->public_dm == false) || $recipient->is_private) {
  353. if($recipient->follows($profile) == true) {
  354. $hidden = false;
  355. } else {
  356. $hidden = true;
  357. }
  358. } else {
  359. $hidden = false;
  360. }
  361. if(config('pixelfed.enforce_account_limit') == true) {
  362. $size = Cache::remember($user->storageUsedKey(), now()->addDays(3), function() use($user) {
  363. return Media::whereUserId($user->id)->sum('size') / 1000;
  364. });
  365. $limit = (int) config('pixelfed.max_account_size');
  366. if ($size >= $limit) {
  367. abort(403, 'Account size limit reached.');
  368. }
  369. }
  370. $photo = $request->file('file');
  371. $mimes = explode(',', config('pixelfed.media_types'));
  372. if(in_array($photo->getMimeType(), $mimes) == false) {
  373. abort(403, 'Invalid or unsupported mime type.');
  374. }
  375. $storagePath = MediaPathService::get($user, 2) . Str::random(8);
  376. $path = $photo->store($storagePath);
  377. $hash = \hash_file('sha256', $photo);
  378. abort_if(MediaBlocklistService::exists($hash) == true, 451);
  379. $status = new Status;
  380. $status->profile_id = $profile->id;
  381. $status->caption = null;
  382. $status->rendered = null;
  383. $status->visibility = 'direct';
  384. $status->scope = 'direct';
  385. $status->in_reply_to_profile_id = $recipient->id;
  386. $status->save();
  387. $media = new Media();
  388. $media->status_id = $status->id;
  389. $media->profile_id = $profile->id;
  390. $media->user_id = $user->id;
  391. $media->media_path = $path;
  392. $media->original_sha256 = $hash;
  393. $media->size = $photo->getSize();
  394. $media->mime = $photo->getMimeType();
  395. $media->caption = null;
  396. $media->filter_class = null;
  397. $media->filter_name = null;
  398. $media->save();
  399. $dm = new DirectMessage;
  400. $dm->to_id = $recipient->id;
  401. $dm->from_id = $profile->id;
  402. $dm->status_id = $status->id;
  403. $dm->type = array_first(explode('/', $media->mime)) == 'video' ? 'video' : 'photo';
  404. $dm->is_hidden = $hidden;
  405. $dm->save();
  406. if($recipient->domain) {
  407. $this->remoteDeliver($dm);
  408. }
  409. return [
  410. 'id' => $dm->id,
  411. 'reportId' => (string) $dm->status_id,
  412. 'type' => $dm->type,
  413. 'url' => $media->url()
  414. ];
  415. }
  416. public function composeLookup(Request $request)
  417. {
  418. $this->validate($request, [
  419. 'q' => 'required|string|min:1|max:50',
  420. 'remote' => 'nullable|boolean',
  421. ]);
  422. $q = $request->input('q');
  423. $r = $request->input('remote');
  424. if($r && Helpers::validateUrl($q)) {
  425. Helpers::profileFetch($q);
  426. }
  427. if(Str::of($q)->startsWith('@')) {
  428. if(strlen($q) < 3) {
  429. return [];
  430. }
  431. if(substr_count($q, '@') == 2) {
  432. WebfingerService::lookup($q);
  433. }
  434. $q = mb_substr($q, 1);
  435. }
  436. $blocked = UserFilter::whereFilterableType('App\Profile')
  437. ->whereFilterType('block')
  438. ->whereFilterableId($request->user()->profile_id)
  439. ->pluck('user_id');
  440. $blocked->push($request->user()->profile_id);
  441. $results = Profile::select('id','domain','username')
  442. ->whereNotIn('id', $blocked)
  443. ->where('username','like','%'.$q.'%')
  444. ->limit(15)
  445. ->get()
  446. ->map(function($r) {
  447. return [
  448. 'local' => (bool) !$r->domain,
  449. 'id' => (string) $r->id,
  450. 'name' => $r->username,
  451. 'privacy' => true,
  452. 'avatar' => $r->avatarUrl()
  453. ];
  454. });
  455. return $results;
  456. }
  457. public function read(Request $request)
  458. {
  459. $this->validate($request, [
  460. 'pid' => 'required',
  461. 'sid' => 'required'
  462. ]);
  463. $pid = $request->input('pid');
  464. $sid = $request->input('sid');
  465. $dms = DirectMessage::whereToId($request->user()->profile_id)
  466. ->whereFromId($pid)
  467. ->where('status_id', '>=', $sid)
  468. ->get();
  469. $now = now();
  470. foreach($dms as $dm) {
  471. $dm->read_at = $now;
  472. $dm->save();
  473. }
  474. return response()->json($dms->pluck('id'));
  475. }
  476. public function mute(Request $request)
  477. {
  478. $this->validate($request, [
  479. 'id' => 'required'
  480. ]);
  481. $fid = $request->input('id');
  482. $pid = $request->user()->profile_id;
  483. UserFilter::firstOrCreate(
  484. [
  485. 'user_id' => $pid,
  486. 'filterable_id' => $fid,
  487. 'filterable_type' => 'App\Profile',
  488. 'filter_type' => 'dm.mute'
  489. ]
  490. );
  491. return [200];
  492. }
  493. public function unmute(Request $request)
  494. {
  495. $this->validate($request, [
  496. 'id' => 'required'
  497. ]);
  498. $fid = $request->input('id');
  499. $pid = $request->user()->profile_id;
  500. $f = UserFilter::whereUserId($pid)
  501. ->whereFilterableId($fid)
  502. ->whereFilterableType('App\Profile')
  503. ->whereFilterType('dm.mute')
  504. ->firstOrFail();
  505. $f->delete();
  506. return [200];
  507. }
  508. public function remoteDeliver($dm)
  509. {
  510. $profile = $dm->author;
  511. $url = $dm->recipient->inbox_url;
  512. $tags = [
  513. [
  514. 'type' => 'Mention',
  515. 'href' => $dm->recipient->permalink(),
  516. 'name' => $dm->recipient->emailUrl(),
  517. ]
  518. ];
  519. $body = [
  520. '@context' => [
  521. 'https://www.w3.org/ns/activitystreams',
  522. 'https://w3id.org/security/v1',
  523. [
  524. 'sc' => 'http://schema.org#',
  525. 'Hashtag' => 'as:Hashtag',
  526. 'sensitive' => 'as:sensitive',
  527. ]
  528. ],
  529. 'id' => $dm->status->permalink(),
  530. 'type' => 'Create',
  531. 'actor' => $dm->status->profile->permalink(),
  532. 'published' => $dm->status->created_at->toAtomString(),
  533. 'to' => [$dm->recipient->permalink()],
  534. 'cc' => [],
  535. 'object' => [
  536. 'id' => $dm->status->url(),
  537. 'type' => 'Note',
  538. 'summary' => null,
  539. 'content' => $dm->status->rendered ?? $dm->status->caption,
  540. 'inReplyTo' => null,
  541. 'published' => $dm->status->created_at->toAtomString(),
  542. 'url' => $dm->status->url(),
  543. 'attributedTo' => $dm->status->profile->permalink(),
  544. 'to' => [$dm->recipient->permalink()],
  545. 'cc' => [],
  546. 'sensitive' => (bool) $dm->status->is_nsfw,
  547. 'attachment' => $dm->status->media()->orderBy('order')->get()->map(function ($media) {
  548. return [
  549. 'type' => $media->activityVerb(),
  550. 'mediaType' => $media->mime,
  551. 'url' => $media->url(),
  552. 'name' => $media->caption,
  553. ];
  554. })->toArray(),
  555. 'tag' => $tags,
  556. ]
  557. ];
  558. Helpers::sendSignedObject($profile, $url, $body);
  559. }
  560. public function remoteDelete($dm)
  561. {
  562. $profile = $dm->author;
  563. $url = $dm->recipient->inbox_url;
  564. $body = [
  565. '@context' => [
  566. 'https://www.w3.org/ns/activitystreams',
  567. 'https://w3id.org/security/v1',
  568. [
  569. 'sc' => 'http://schema.org#',
  570. 'Hashtag' => 'as:Hashtag',
  571. 'sensitive' => 'as:sensitive',
  572. ]
  573. ],
  574. 'id' => $dm->status->permalink('#delete'),
  575. 'to' => [
  576. 'https://www.w3.org/ns/activitystreams#Public'
  577. ],
  578. 'type' => 'Delete',
  579. 'actor' => $dm->status->profile->permalink(),
  580. 'object' => [
  581. 'id' => $dm->status->url(),
  582. 'type' => 'Tombstone'
  583. ]
  584. ];
  585. Helpers::sendSignedObject($profile, $url, $body);
  586. }
  587. }