StoryController.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  1. <?php
  2. namespace App\Http\Controllers;
  3. use Illuminate\Http\Request;
  4. use Illuminate\Support\Str;
  5. use App\Media;
  6. use App\Profile;
  7. use App\Story;
  8. use App\StoryView;
  9. use App\Services\StoryService;
  10. use Cache, Storage;
  11. use Image as Intervention;
  12. use App\Services\FollowerService;
  13. use App\Services\MediaPathService;
  14. use FFMpeg;
  15. use FFMpeg\Coordinate\Dimension;
  16. use FFMpeg\Format\Video\X264;
  17. class StoryController extends Controller
  18. {
  19. public function apiV1Add(Request $request)
  20. {
  21. abort_if(!config_cache('instance.stories.enabled') || !$request->user(), 404);
  22. $this->validate($request, [
  23. 'file' => function() {
  24. return [
  25. 'required',
  26. 'mimes:image/jpeg,image/png,video/mp4',
  27. 'max:' . config_cache('pixelfed.max_photo_size'),
  28. ];
  29. },
  30. ]);
  31. $user = $request->user();
  32. if(Story::whereProfileId($user->profile_id)->where('expires_at', '>', now())->count() >= Story::MAX_PER_DAY) {
  33. abort(400, 'You have reached your limit for new Stories today.');
  34. }
  35. $photo = $request->file('file');
  36. $path = $this->storePhoto($photo, $user);
  37. $story = new Story();
  38. $story->duration = 3;
  39. $story->profile_id = $user->profile_id;
  40. $story->type = Str::endsWith($photo->getMimeType(), 'mp4') ? 'video' :'photo';
  41. $story->mime = $photo->getMimeType();
  42. $story->path = $path;
  43. $story->local = true;
  44. $story->size = $photo->getSize();
  45. $story->save();
  46. $url = $story->path;
  47. if($story->type === 'video') {
  48. $video = FFMpeg::open($path);
  49. $width = $video->getVideoStream()->get('width');
  50. $height = $video->getVideoStream()->get('height');
  51. if($width !== 1080 || $height !== 1920) {
  52. Storage::delete($story->path);
  53. $story->delete();
  54. abort(422, 'Invalid video dimensions, must be 1080x1920');
  55. }
  56. }
  57. return [
  58. 'code' => 200,
  59. 'msg' => 'Successfully added',
  60. 'media_id' => (string) $story->id,
  61. 'media_url' => url(Storage::url($url)) . '?v=' . time(),
  62. 'media_type' => $story->type
  63. ];
  64. }
  65. protected function storePhoto($photo, $user)
  66. {
  67. $mimes = explode(',', config_cache('pixelfed.media_types'));
  68. if(in_array($photo->getMimeType(), [
  69. 'image/jpeg',
  70. 'image/png',
  71. 'video/mp4'
  72. ]) == false) {
  73. abort(400, 'Invalid media type');
  74. return;
  75. }
  76. $storagePath = MediaPathService::story($user->profile);
  77. $path = $photo->store($storagePath);
  78. if(in_array($photo->getMimeType(), ['image/jpeg','image/png'])) {
  79. $fpath = storage_path('app/' . $path);
  80. $img = Intervention::make($fpath);
  81. $img->orientate();
  82. $img->save($fpath, config_cache('pixelfed.image_quality'));
  83. $img->destroy();
  84. }
  85. return $path;
  86. }
  87. public function cropPhoto(Request $request)
  88. {
  89. abort_if(!config_cache('instance.stories.enabled') || !$request->user(), 404);
  90. $this->validate($request, [
  91. 'media_id' => 'required|integer|min:1',
  92. 'width' => 'required',
  93. 'height' => 'required',
  94. 'x' => 'required',
  95. 'y' => 'required'
  96. ]);
  97. $user = $request->user();
  98. $id = $request->input('media_id');
  99. $width = round($request->input('width'));
  100. $height = round($request->input('height'));
  101. $x = round($request->input('x'));
  102. $y = round($request->input('y'));
  103. $story = Story::whereProfileId($user->profile_id)->findOrFail($id);
  104. $path = storage_path('app/' . $story->path);
  105. if(!is_file($path)) {
  106. abort(400, 'Invalid or missing media.');
  107. }
  108. if($story->type === 'photo') {
  109. $img = Intervention::make($path);
  110. $img->crop($width, $height, $x, $y);
  111. $img->resize(1080, 1920, function ($constraint) {
  112. $constraint->aspectRatio();
  113. });
  114. $img->save($path, config_cache('pixelfed.image_quality'));
  115. }
  116. return [
  117. 'code' => 200,
  118. 'msg' => 'Successfully cropped',
  119. ];
  120. }
  121. public function publishStory(Request $request)
  122. {
  123. abort_if(!config_cache('instance.stories.enabled') || !$request->user(), 404);
  124. $this->validate($request, [
  125. 'media_id' => 'required',
  126. 'duration' => 'required|integer|min:3|max:10'
  127. ]);
  128. $id = $request->input('media_id');
  129. $user = $request->user();
  130. $story = Story::whereProfileId($user->profile_id)
  131. ->findOrFail($id);
  132. $story->active = true;
  133. $story->duration = $request->input('duration', 10);
  134. $story->expires_at = now()->addMinutes(1450);
  135. $story->save();
  136. return [
  137. 'code' => 200,
  138. 'msg' => 'Successfully published',
  139. ];
  140. }
  141. public function apiV1Delete(Request $request, $id)
  142. {
  143. abort_if(!config_cache('instance.stories.enabled') || !$request->user(), 404);
  144. $user = $request->user();
  145. $story = Story::whereProfileId($user->profile_id)
  146. ->findOrFail($id);
  147. if(Storage::exists($story->path) == true) {
  148. Storage::delete($story->path);
  149. }
  150. $story->delete();
  151. return [
  152. 'code' => 200,
  153. 'msg' => 'Successfully deleted'
  154. ];
  155. }
  156. public function apiV1Recent(Request $request)
  157. {
  158. abort_if(!config_cache('instance.stories.enabled') || !$request->user(), 404);
  159. $profile = $request->user()->profile;
  160. $following = $profile->following->pluck('id')->toArray();
  161. if(config('database.default') == 'pgsql') {
  162. $db = Story::with('profile')
  163. ->whereActive(true)
  164. ->whereIn('profile_id', $following)
  165. ->where('expires_at', '>', now())
  166. ->distinct('profile_id')
  167. ->take(9)
  168. ->get();
  169. } else {
  170. $db = Story::with('profile')
  171. ->whereActive(true)
  172. ->whereIn('profile_id', $following)
  173. ->where('created_at', '>', now()->subDay())
  174. ->orderByDesc('expires_at')
  175. ->groupBy('profile_id')
  176. ->take(9)
  177. ->get();
  178. }
  179. $stories = $db->map(function($s, $k) {
  180. return [
  181. 'id' => (string) $s->id,
  182. 'photo' => $s->profile->avatarUrl(),
  183. 'name' => $s->profile->username,
  184. 'link' => $s->profile->url(),
  185. 'lastUpdated' => (int) $s->created_at->format('U'),
  186. 'seen' => $s->seen(),
  187. 'items' => [],
  188. 'pid' => (string) $s->profile->id
  189. ];
  190. });
  191. return response()->json($stories, 200, [], JSON_PRETTY_PRINT|JSON_UNESCAPED_SLASHES);
  192. }
  193. public function apiV1Fetch(Request $request, $id)
  194. {
  195. abort_if(!config_cache('instance.stories.enabled') || !$request->user(), 404);
  196. $authed = $request->user()->profile;
  197. $profile = Profile::findOrFail($id);
  198. if($id == $authed->id) {
  199. $publicOnly = true;
  200. } else {
  201. $publicOnly = (bool) $profile->followedBy($authed);
  202. }
  203. $stories = Story::whereProfileId($profile->id)
  204. ->whereActive(true)
  205. ->orderBy('expires_at', 'desc')
  206. ->where('expires_at', '>', now())
  207. ->when(!$publicOnly, function($query, $publicOnly) {
  208. return $query->wherePublic(true);
  209. })
  210. ->get()
  211. ->map(function($s, $k) {
  212. return [
  213. 'id' => (string) $s->id,
  214. 'type' => Str::endsWith($s->path, '.mp4') ? 'video' :'photo',
  215. 'length' => 3,
  216. 'src' => url(Storage::url($s->path)),
  217. 'preview' => null,
  218. 'link' => null,
  219. 'linkText' => null,
  220. 'time' => $s->created_at->format('U'),
  221. 'expires_at' => (int) $s->expires_at->format('U'),
  222. 'created_ago' => $s->created_at->diffForHumans(null, true, true),
  223. 'seen' => $s->seen()
  224. ];
  225. })->toArray();
  226. return response()->json($stories, 200, [], JSON_PRETTY_PRINT|JSON_UNESCAPED_SLASHES);
  227. }
  228. public function apiV1Item(Request $request, $id)
  229. {
  230. abort_if(!config_cache('instance.stories.enabled') || !$request->user(), 404);
  231. $authed = $request->user()->profile;
  232. $story = Story::with('profile')
  233. ->whereActive(true)
  234. ->where('expires_at', '>', now())
  235. ->findOrFail($id);
  236. $profile = $story->profile;
  237. if($story->profile_id == $authed->id) {
  238. $publicOnly = true;
  239. } else {
  240. $publicOnly = (bool) $profile->followedBy($authed);
  241. }
  242. abort_if(!$publicOnly, 403);
  243. $res = [
  244. 'id' => (string) $story->id,
  245. 'type' => Str::endsWith($story->path, '.mp4') ? 'video' :'photo',
  246. 'length' => 10,
  247. 'src' => url(Storage::url($story->path)),
  248. 'preview' => null,
  249. 'link' => null,
  250. 'linkText' => null,
  251. 'time' => $story->created_at->format('U'),
  252. 'expires_at' => (int) $story->expires_at->format('U'),
  253. 'seen' => $story->seen()
  254. ];
  255. return response()->json($res, 200, [], JSON_PRETTY_PRINT|JSON_UNESCAPED_SLASHES);
  256. }
  257. public function apiV1Profile(Request $request, $id)
  258. {
  259. abort_if(!config_cache('instance.stories.enabled') || !$request->user(), 404);
  260. $authed = $request->user()->profile;
  261. $profile = Profile::findOrFail($id);
  262. if($id == $authed->id) {
  263. $publicOnly = true;
  264. } else {
  265. $publicOnly = (bool) $profile->followedBy($authed);
  266. }
  267. $stories = Story::whereProfileId($profile->id)
  268. ->whereActive(true)
  269. ->orderBy('expires_at')
  270. ->where('expires_at', '>', now())
  271. ->when(!$publicOnly, function($query, $publicOnly) {
  272. return $query->wherePublic(true);
  273. })
  274. ->get()
  275. ->map(function($s, $k) {
  276. return [
  277. 'id' => $s->id,
  278. 'type' => Str::endsWith($s->path, '.mp4') ? 'video' :'photo',
  279. 'length' => 10,
  280. 'src' => url(Storage::url($s->path)),
  281. 'preview' => null,
  282. 'link' => null,
  283. 'linkText' => null,
  284. 'time' => $s->created_at->format('U'),
  285. 'expires_at' => (int) $s->expires_at->format('U'),
  286. 'seen' => $s->seen()
  287. ];
  288. })->toArray();
  289. if(count($stories) == 0) {
  290. return [];
  291. }
  292. $cursor = count($stories) - 1;
  293. $stories = [[
  294. 'id' => (string) $stories[$cursor]['id'],
  295. 'photo' => $profile->avatarUrl(),
  296. 'name' => $profile->username,
  297. 'link' => $profile->url(),
  298. 'lastUpdated' => (int) now()->format('U'),
  299. 'seen' => null,
  300. 'items' => $stories,
  301. 'pid' => (string) $profile->id
  302. ]];
  303. return response()->json($stories, 200, [], JSON_PRETTY_PRINT|JSON_UNESCAPED_SLASHES);
  304. }
  305. public function apiV1Viewed(Request $request)
  306. {
  307. abort_if(!config_cache('instance.stories.enabled') || !$request->user(), 404);
  308. $this->validate($request, [
  309. 'id' => 'required|integer|min:1|exists:stories',
  310. ]);
  311. $id = $request->input('id');
  312. $authed = $request->user()->profile;
  313. $story = Story::with('profile')
  314. ->where('expires_at', '>', now())
  315. ->orderByDesc('expires_at')
  316. ->findOrFail($id);
  317. $profile = $story->profile;
  318. if($story->profile_id == $authed->id) {
  319. return [];
  320. }
  321. $publicOnly = (bool) $profile->followedBy($authed);
  322. abort_if(!$publicOnly, 403);
  323. StoryView::firstOrCreate([
  324. 'story_id' => $id,
  325. 'profile_id' => $authed->id
  326. ]);
  327. $story->view_count = $story->view_count + 1;
  328. $story->save();
  329. return ['code' => 200];
  330. }
  331. public function apiV1Exists(Request $request, $id)
  332. {
  333. abort_if(!config_cache('instance.stories.enabled') || !$request->user(), 404);
  334. $res = (bool) Story::whereProfileId($id)
  335. ->whereActive(true)
  336. ->where('expires_at', '>', now())
  337. ->count();
  338. return response()->json($res);
  339. }
  340. public function apiV1Me(Request $request)
  341. {
  342. abort_if(!config_cache('instance.stories.enabled') || !$request->user(), 404);
  343. $profile = $request->user()->profile;
  344. $stories = Story::whereProfileId($profile->id)
  345. ->whereActive(true)
  346. ->orderBy('expires_at')
  347. ->where('expires_at', '>', now())
  348. ->get()
  349. ->map(function($s, $k) {
  350. return [
  351. 'id' => $s->id,
  352. 'type' => Str::endsWith($s->path, '.mp4') ? 'video' :'photo',
  353. 'length' => 3,
  354. 'src' => url(Storage::url($s->path)),
  355. 'preview' => null,
  356. 'link' => null,
  357. 'linkText' => null,
  358. 'time' => $s->created_at->format('U'),
  359. 'expires_at' => (int) $s->expires_at->format('U'),
  360. 'seen' => true
  361. ];
  362. })->toArray();
  363. $ts = count($stories) ? last($stories)['time'] : null;
  364. $res = [
  365. 'id' => (string) $profile->id,
  366. 'photo' => $profile->avatarUrl(),
  367. 'name' => $profile->username,
  368. 'link' => $profile->url(),
  369. 'lastUpdated' => $ts,
  370. 'seen' => true,
  371. 'items' => $stories
  372. ];
  373. return response()->json($res, 200, [], JSON_PRETTY_PRINT|JSON_UNESCAPED_SLASHES);
  374. }
  375. public function compose(Request $request)
  376. {
  377. abort_if(!config_cache('instance.stories.enabled') || !$request->user(), 404);
  378. return view('stories.compose');
  379. }
  380. public function iRedirect(Request $request)
  381. {
  382. abort_if(!config_cache('instance.stories.enabled') || !$request->user(), 404);
  383. $user = $request->user();
  384. abort_if(!$user, 404);
  385. $username = $user->username;
  386. return redirect("/stories/{$username}");
  387. }
  388. }