StoryComposeController.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574
  1. <?php
  2. namespace App\Http\Controllers;
  3. use App\DirectMessage;
  4. use App\Jobs\StoryPipeline\StoryDelete;
  5. use App\Jobs\StoryPipeline\StoryFanout;
  6. use App\Jobs\StoryPipeline\StoryReactionDeliver;
  7. use App\Jobs\StoryPipeline\StoryReplyDeliver;
  8. use App\Models\Conversation;
  9. use App\Models\Poll;
  10. use App\Models\PollVote;
  11. use App\Notification;
  12. use App\Report;
  13. use App\Services\FollowerService;
  14. use App\Services\MediaPathService;
  15. use App\Services\StoryIndexService;
  16. use App\Services\StoryService;
  17. use App\Services\UserRoleService;
  18. use App\Status;
  19. use App\Story;
  20. use FFMpeg;
  21. use Illuminate\Http\Request;
  22. use Illuminate\Support\Str;
  23. use Intervention\Image\Encoders\JpegEncoder;
  24. use Intervention\Image\Encoders\PngEncoder;
  25. use Intervention\Image\ImageManager;
  26. use Storage;
  27. class StoryComposeController extends Controller
  28. {
  29. protected $imageManager;
  30. public function __construct()
  31. {
  32. $driver = match (config('image.driver')) {
  33. 'imagick' => \Intervention\Image\Drivers\Imagick\Driver::class,
  34. 'vips' => \Intervention\Image\Drivers\Vips\Driver::class,
  35. default => \Intervention\Image\Drivers\Gd\Driver::class
  36. };
  37. $this->imageManager = new ImageManager(
  38. $driver,
  39. autoOrientation: true,
  40. decodeAnimation: true,
  41. blendingColor: 'ffffff',
  42. strip: true
  43. );
  44. }
  45. public function apiV1Add(Request $request)
  46. {
  47. abort_if(! (bool) config_cache('instance.stories.enabled') || ! $request->user(), 404);
  48. $this->validate($request, [
  49. 'file' => function () {
  50. return [
  51. 'required',
  52. 'mimetypes:image/jpeg,image/png,video/mp4,image/jpg',
  53. 'max:'.config_cache('pixelfed.max_photo_size'),
  54. ];
  55. },
  56. ]);
  57. $user = $request->user();
  58. abort_if($user->has_roles && ! UserRoleService::can('can-use-stories', $user->id), 403, 'Invalid permissions for this action');
  59. $count = Story::whereProfileId($user->profile_id)
  60. ->whereActive(true)
  61. ->where('expires_at', '>', now())
  62. ->count();
  63. if ($count >= Story::MAX_PER_DAY) {
  64. abort(418, 'You have reached your limit for new Stories today.');
  65. }
  66. $photo = $request->file('file');
  67. $path = $this->storePhoto($photo, $user);
  68. $story = new Story;
  69. $story->duration = 3;
  70. $story->profile_id = $user->profile_id;
  71. $story->type = Str::endsWith($photo->getMimeType(), 'mp4') ? 'video' : 'photo';
  72. $story->mime = $photo->getMimeType();
  73. $story->path = $path;
  74. $story->local = true;
  75. $story->size = $photo->getSize();
  76. $story->bearcap_token = str_random(64);
  77. $story->expires_at = now()->addMinutes(1440);
  78. $story->save();
  79. $url = $story->path;
  80. $res = [
  81. 'code' => 200,
  82. 'msg' => 'Successfully added',
  83. 'media_id' => (string) $story->id,
  84. 'media_url' => url(Storage::url($url)).'?v='.time(),
  85. 'media_type' => $story->type,
  86. ];
  87. if ($story->type === 'video') {
  88. $video = FFMpeg::open($path);
  89. $duration = $video->getDurationInSeconds();
  90. $res['media_duration'] = $duration;
  91. if ($duration > 500) {
  92. Storage::delete($story->path);
  93. $story->delete();
  94. return response()->json([
  95. 'message' => 'Video duration cannot exceed 60 seconds',
  96. ], 422);
  97. }
  98. }
  99. return $res;
  100. }
  101. protected function storePhoto($photo, $user)
  102. {
  103. $mimes = explode(',', config_cache('pixelfed.media_types'));
  104. if (in_array($photo->getMimeType(), [
  105. 'image/jpeg',
  106. 'image/png',
  107. 'video/mp4',
  108. ]) == false) {
  109. abort(400, 'Invalid media type');
  110. return;
  111. }
  112. $storagePath = MediaPathService::story($user->profile);
  113. $path = $photo->storePubliclyAs($storagePath, Str::random(random_int(2, 12)).'_'.Str::random(random_int(32, 35)).'_'.Str::random(random_int(1, 14)).'.'.$photo->extension());
  114. if (in_array($photo->getMimeType(), ['image/jpeg', 'image/jpg', 'image/png'])) {
  115. $fpath = storage_path('app/'.$path);
  116. $img = $this->imageManager->read($fpath);
  117. $quality = config_cache('pixelfed.image_quality');
  118. $encoder = in_array($photo->getMimeType(), ['image/jpeg', 'image/jpg']) ?
  119. new JpegEncoder($quality) :
  120. new PngEncoder;
  121. $encoded = $img->encode($encoder);
  122. file_put_contents($fpath, $encoded);
  123. }
  124. return $path;
  125. }
  126. public function cropPhoto(Request $request)
  127. {
  128. abort_if(! (bool) config_cache('instance.stories.enabled') || ! $request->user(), 404);
  129. $this->validate($request, [
  130. 'media_id' => 'required|integer|min:1',
  131. 'width' => 'required',
  132. 'height' => 'required',
  133. 'x' => 'required',
  134. 'y' => 'required',
  135. ]);
  136. $user = $request->user();
  137. $id = $request->input('media_id');
  138. $width = round($request->input('width'));
  139. $height = round($request->input('height'));
  140. $x = round($request->input('x'));
  141. $y = round($request->input('y'));
  142. $story = Story::whereProfileId($user->profile_id)->findOrFail($id);
  143. $path = storage_path('app/'.$story->path);
  144. if (! is_file($path)) {
  145. abort(400, 'Invalid or missing media.');
  146. }
  147. if ($story->type === 'photo') {
  148. $img = $this->imageManager->read($path);
  149. $img = $img->crop($width, $height, $x, $y);
  150. $img = $img->resize(1080, 1920, function ($constraint) {
  151. $constraint->aspectRatio();
  152. $constraint->upsize();
  153. });
  154. $quality = config_cache('pixelfed.image_quality');
  155. $extension = pathinfo($path, PATHINFO_EXTENSION);
  156. if (in_array(strtolower($extension), ['jpg', 'jpeg'])) {
  157. $encoder = new JpegEncoder($quality);
  158. } else {
  159. $encoder = new PngEncoder;
  160. }
  161. $encoded = $img->encode($encoder);
  162. file_put_contents($path, $encoded);
  163. }
  164. return [
  165. 'code' => 200,
  166. 'msg' => 'Successfully cropped',
  167. ];
  168. }
  169. public function publishStory(Request $request)
  170. {
  171. abort_if(! (bool) config_cache('instance.stories.enabled') || ! $request->user(), 404);
  172. $this->validate($request, [
  173. 'media_id' => 'required',
  174. 'duration' => 'required|integer|min:3|max:120',
  175. 'can_reply' => 'required|boolean',
  176. 'can_react' => 'required|boolean',
  177. ]);
  178. $id = $request->input('media_id');
  179. $user = $request->user();
  180. abort_if($user->has_roles && ! UserRoleService::can('can-use-stories', $user->id), 403, 'Invalid permissions for this action');
  181. $story = Story::whereProfileId($user->profile_id)
  182. ->findOrFail($id);
  183. $story->active = true;
  184. $story->duration = $request->input('duration', 10);
  185. $story->can_reply = $request->input('can_reply');
  186. $story->can_react = $request->input('can_react');
  187. $story->save();
  188. $index = app(StoryIndexService::class);
  189. $index->indexStory($story);
  190. StoryService::delLatest($story->profile_id);
  191. StoryFanout::dispatch($story)->onQueue('story');
  192. StoryService::addRotateQueue($story->id);
  193. return [
  194. 'code' => 200,
  195. 'msg' => 'Successfully published',
  196. ];
  197. }
  198. public function apiV1Delete(Request $request, $id)
  199. {
  200. abort_if(! (bool) config_cache('instance.stories.enabled') || ! $request->user(), 404);
  201. $user = $request->user();
  202. $story = Story::whereProfileId($user->profile_id)
  203. ->findOrFail($id);
  204. $story->active = false;
  205. $story->save();
  206. $index = app(StoryIndexService::class);
  207. $index->removeStory($story->id, $story->profile_id);
  208. StoryDelete::dispatch($story)->onQueue('story');
  209. return [
  210. 'code' => 200,
  211. 'msg' => 'Successfully deleted',
  212. ];
  213. }
  214. public function compose(Request $request)
  215. {
  216. abort_if(! (bool) config_cache('instance.stories.enabled') || ! $request->user(), 404);
  217. $user = $request->user();
  218. abort_if($user->has_roles && ! UserRoleService::can('can-use-stories', $user->id), 403, 'Invalid permissions for this action');
  219. return view('stories.compose');
  220. }
  221. public function createPoll(Request $request)
  222. {
  223. abort_if(! (bool) config_cache('instance.stories.enabled') || ! $request->user(), 404);
  224. abort_if(! config_cache('instance.polls.enabled'), 404);
  225. return $request->all();
  226. }
  227. public function publishStoryPoll(Request $request)
  228. {
  229. abort_if(! (bool) config_cache('instance.stories.enabled') || ! $request->user(), 404);
  230. $this->validate($request, [
  231. 'question' => 'required|string|min:6|max:140',
  232. 'options' => 'required|array|min:2|max:4',
  233. 'can_reply' => 'required|boolean',
  234. 'can_react' => 'required|boolean',
  235. ]);
  236. $user = $request->user();
  237. abort_if($user->has_roles && ! UserRoleService::can('can-use-stories', $user->id), 403, 'Invalid permissions for this action');
  238. $pid = $request->user()->profile_id;
  239. $count = Story::whereProfileId($pid)
  240. ->whereActive(true)
  241. ->where('expires_at', '>', now())
  242. ->count();
  243. if ($count >= Story::MAX_PER_DAY) {
  244. abort(418, 'You have reached your limit for new Stories today.');
  245. }
  246. $story = new Story;
  247. $story->type = 'poll';
  248. $story->story = json_encode([
  249. 'question' => $request->input('question'),
  250. 'options' => $request->input('options'),
  251. ]);
  252. $story->public = false;
  253. $story->local = true;
  254. $story->profile_id = $pid;
  255. $story->expires_at = now()->addMinutes(1440);
  256. $story->duration = 30;
  257. $story->can_reply = false;
  258. $story->can_react = false;
  259. $story->save();
  260. $poll = new Poll;
  261. $poll->story_id = $story->id;
  262. $poll->profile_id = $pid;
  263. $poll->poll_options = $request->input('options');
  264. $poll->expires_at = $story->expires_at;
  265. $poll->cached_tallies = collect($poll->poll_options)->map(function ($o) {
  266. return 0;
  267. })->toArray();
  268. $poll->save();
  269. $story->active = true;
  270. $story->save();
  271. StoryService::delLatest($story->profile_id);
  272. return [
  273. 'code' => 200,
  274. 'msg' => 'Successfully published',
  275. ];
  276. }
  277. public function storyPollVote(Request $request)
  278. {
  279. abort_if(! (bool) config_cache('instance.stories.enabled') || ! $request->user(), 404);
  280. $this->validate($request, [
  281. 'sid' => 'required',
  282. 'ci' => 'required|integer|min:0|max:3',
  283. ]);
  284. $pid = $request->user()->profile_id;
  285. $ci = $request->input('ci');
  286. $story = Story::findOrFail($request->input('sid'));
  287. abort_if(! FollowerService::follows($pid, $story->profile_id), 403);
  288. $poll = Poll::whereStoryId($story->id)->firstOrFail();
  289. $vote = new PollVote;
  290. $vote->profile_id = $pid;
  291. $vote->poll_id = $poll->id;
  292. $vote->story_id = $story->id;
  293. $vote->status_id = null;
  294. $vote->choice = $ci;
  295. $vote->save();
  296. $poll->votes_count = $poll->votes_count + 1;
  297. $poll->cached_tallies = collect($poll->getTallies())->map(function ($tally, $key) use ($ci) {
  298. return $ci == $key ? $tally + 1 : $tally;
  299. })->toArray();
  300. $poll->save();
  301. return 200;
  302. }
  303. public function storeReport(Request $request)
  304. {
  305. abort_if(! (bool) config_cache('instance.stories.enabled') || ! $request->user(), 404);
  306. $this->validate($request, [
  307. 'type' => 'required|alpha_dash',
  308. 'id' => 'required|integer|min:1',
  309. ]);
  310. $user = $request->user();
  311. abort_if($user->has_roles && ! UserRoleService::can('can-use-stories', $user->id), 403, 'Invalid permissions for this action');
  312. $pid = $request->user()->profile_id;
  313. $sid = $request->input('id');
  314. $type = $request->input('type');
  315. $types = [
  316. // original 3
  317. 'spam',
  318. 'sensitive',
  319. 'abusive',
  320. // new
  321. 'underage',
  322. 'copyright',
  323. 'impersonation',
  324. 'scam',
  325. 'terrorism',
  326. ];
  327. abort_if(! in_array($type, $types), 422, 'Invalid story report type');
  328. $story = Story::findOrFail($sid);
  329. abort_if($story->profile_id == $pid, 422, 'Cannot report your own story');
  330. abort_if(! FollowerService::follows($pid, $story->profile_id), 422, 'Cannot report a story from an account you do not follow');
  331. if (Report::whereProfileId($pid)
  332. ->whereObjectType('App\Story')
  333. ->whereObjectId($story->id)
  334. ->exists()
  335. ) {
  336. return response()->json(['error' => [
  337. 'code' => 409,
  338. 'message' => 'Cannot report the same story again',
  339. ]], 409);
  340. }
  341. $report = new Report;
  342. $report->profile_id = $pid;
  343. $report->user_id = $request->user()->id;
  344. $report->object_id = $story->id;
  345. $report->object_type = 'App\Story';
  346. $report->reported_profile_id = $story->profile_id;
  347. $report->type = $type;
  348. $report->message = null;
  349. $report->save();
  350. return [200];
  351. }
  352. public function react(Request $request)
  353. {
  354. abort_if(! (bool) config_cache('instance.stories.enabled') || ! $request->user(), 404);
  355. $this->validate($request, [
  356. 'sid' => 'required',
  357. 'reaction' => 'required|string',
  358. ]);
  359. $pid = $request->user()->profile_id;
  360. $text = $request->input('reaction');
  361. $user = $request->user();
  362. abort_if($user->has_roles && ! UserRoleService::can('can-use-stories', $user->id), 403, 'Invalid permissions for this action');
  363. $story = Story::findOrFail($request->input('sid'));
  364. abort_if(! $story->can_react, 422);
  365. abort_if(StoryService::reactCounter($story->id, $pid) >= 5, 422, 'You have already reacted to this story');
  366. $status = new Status;
  367. $status->profile_id = $pid;
  368. $status->type = 'story:reaction';
  369. $status->caption = $text;
  370. $status->scope = 'direct';
  371. $status->visibility = 'direct';
  372. $status->in_reply_to_profile_id = $story->profile_id;
  373. $status->entities = json_encode([
  374. 'story_id' => $story->id,
  375. 'reaction' => $text,
  376. ]);
  377. $status->save();
  378. $dm = new DirectMessage;
  379. $dm->to_id = $story->profile_id;
  380. $dm->from_id = $pid;
  381. $dm->type = 'story:react';
  382. $dm->status_id = $status->id;
  383. $dm->meta = json_encode([
  384. 'story_username' => $story->profile->username,
  385. 'story_actor_username' => $request->user()->username,
  386. 'story_id' => $story->id,
  387. 'story_media_url' => url(Storage::url($story->path)),
  388. 'reaction' => $text,
  389. ]);
  390. $dm->save();
  391. Conversation::updateOrInsert(
  392. [
  393. 'to_id' => $story->profile_id,
  394. 'from_id' => $pid,
  395. ],
  396. [
  397. 'type' => 'story:react',
  398. 'status_id' => $status->id,
  399. 'dm_id' => $dm->id,
  400. 'is_hidden' => false,
  401. ]
  402. );
  403. if ($story->local) {
  404. // generate notification
  405. $n = new Notification;
  406. $n->profile_id = $dm->to_id;
  407. $n->actor_id = $dm->from_id;
  408. $n->item_id = $dm->id;
  409. $n->item_type = 'App\DirectMessage';
  410. $n->action = 'story:react';
  411. $n->save();
  412. } else {
  413. StoryReactionDeliver::dispatch($story, $status)->onQueue('story');
  414. }
  415. StoryService::reactIncrement($story->id, $pid);
  416. return 200;
  417. }
  418. public function comment(Request $request)
  419. {
  420. abort_if(! (bool) config_cache('instance.stories.enabled') || ! $request->user(), 404);
  421. $this->validate($request, [
  422. 'sid' => 'required',
  423. 'caption' => 'required|string',
  424. ]);
  425. $pid = $request->user()->profile_id;
  426. $text = $request->input('caption');
  427. $user = $request->user();
  428. abort_if($user->has_roles && ! UserRoleService::can('can-use-stories', $user->id), 403, 'Invalid permissions for this action');
  429. $story = Story::findOrFail($request->input('sid'));
  430. abort_if(! $story->can_reply, 422);
  431. $status = new Status;
  432. $status->type = 'story:reply';
  433. $status->profile_id = $pid;
  434. $status->caption = $text;
  435. $status->scope = 'direct';
  436. $status->visibility = 'direct';
  437. $status->in_reply_to_profile_id = $story->profile_id;
  438. $status->entities = json_encode([
  439. 'story_id' => $story->id,
  440. ]);
  441. $status->save();
  442. $dm = new DirectMessage;
  443. $dm->to_id = $story->profile_id;
  444. $dm->from_id = $pid;
  445. $dm->type = 'story:comment';
  446. $dm->status_id = $status->id;
  447. $dm->meta = json_encode([
  448. 'story_username' => $story->profile->username,
  449. 'story_actor_username' => $request->user()->username,
  450. 'story_id' => $story->id,
  451. 'story_media_url' => url(Storage::url($story->path)),
  452. 'caption' => $text,
  453. ]);
  454. $dm->save();
  455. Conversation::updateOrInsert(
  456. [
  457. 'to_id' => $story->profile_id,
  458. 'from_id' => $pid,
  459. ],
  460. [
  461. 'type' => 'story:comment',
  462. 'status_id' => $status->id,
  463. 'dm_id' => $dm->id,
  464. 'is_hidden' => false,
  465. ]
  466. );
  467. if ($story->local) {
  468. // generate notification
  469. $n = new Notification;
  470. $n->profile_id = $dm->to_id;
  471. $n->actor_id = $dm->from_id;
  472. $n->item_id = $dm->id;
  473. $n->item_type = 'App\DirectMessage';
  474. $n->action = 'story:comment';
  475. $n->save();
  476. } else {
  477. StoryReplyDeliver::dispatch($story, $status)->onQueue('story');
  478. }
  479. return 200;
  480. }
  481. }