ApiV1Controller.php 68 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647
  1. <?php
  2. namespace App\Http\Controllers\Api;
  3. use Illuminate\Http\Request;
  4. use App\Http\Controllers\Controller;
  5. use Illuminate\Support\Str;
  6. use App\Util\ActivityPub\Helpers;
  7. use App\Util\Media\Filter;
  8. use Laravel\Passport\Passport;
  9. use Auth, Cache, DB, URL;
  10. use App\{
  11. Avatar,
  12. Bookmark,
  13. DirectMessage,
  14. Follower,
  15. FollowRequest,
  16. Hashtag,
  17. Instance,
  18. Like,
  19. Media,
  20. Notification,
  21. Profile,
  22. Status,
  23. StatusHashtag,
  24. User,
  25. UserSetting,
  26. UserFilter,
  27. };
  28. use League\Fractal;
  29. use App\Transformer\Api\Mastodon\v1\{
  30. AccountTransformer,
  31. MediaTransformer,
  32. NotificationTransformer,
  33. StatusTransformer,
  34. };
  35. use App\Transformer\Api\{
  36. RelationshipTransformer,
  37. };
  38. use App\Http\Controllers\FollowerController;
  39. use League\Fractal\Serializer\ArraySerializer;
  40. use League\Fractal\Pagination\IlluminatePaginatorAdapter;
  41. use App\Http\Controllers\StatusController;
  42. use App\Jobs\AvatarPipeline\AvatarOptimize;
  43. use App\Jobs\CommentPipeline\CommentPipeline;
  44. use App\Jobs\LikePipeline\LikePipeline;
  45. use App\Jobs\SharePipeline\SharePipeline;
  46. use App\Jobs\SharePipeline\UndoSharePipeline;
  47. use App\Jobs\StatusPipeline\NewStatusPipeline;
  48. use App\Jobs\StatusPipeline\StatusDelete;
  49. use App\Jobs\FollowPipeline\FollowPipeline;
  50. use App\Jobs\ImageOptimizePipeline\ImageOptimize;
  51. use App\Jobs\VideoPipeline\{
  52. VideoOptimize,
  53. VideoPostProcess,
  54. VideoThumbnail
  55. };
  56. use App\Services\{
  57. AccountService,
  58. FollowerService,
  59. InstanceService,
  60. LikeService,
  61. NotificationService,
  62. MediaPathService,
  63. PublicTimelineService,
  64. ReblogService,
  65. RelationshipService,
  66. SearchApiV2Service,
  67. StatusService,
  68. MediaBlocklistService,
  69. SnowflakeService,
  70. UserFilterService
  71. };
  72. use App\Util\Lexer\Autolink;
  73. use App\Util\Lexer\PrettyNumber;
  74. use App\Util\Localization\Localization;
  75. use App\Util\Media\License;
  76. use App\Jobs\MediaPipeline\MediaSyncLicensePipeline;
  77. use App\Services\DiscoverService;
  78. use App\Services\CustomEmojiService;
  79. class ApiV1Controller extends Controller
  80. {
  81. protected $fractal;
  82. public function __construct()
  83. {
  84. $this->fractal = new Fractal\Manager();
  85. $this->fractal->setSerializer(new ArraySerializer());
  86. }
  87. public function apps(Request $request)
  88. {
  89. abort_if(!config_cache('pixelfed.oauth_enabled'), 404);
  90. $this->validate($request, [
  91. 'client_name' => 'required',
  92. 'redirect_uris' => 'required',
  93. 'scopes' => 'nullable',
  94. 'website' => 'nullable'
  95. ]);
  96. $uris = implode(',', explode('\n', $request->redirect_uris));
  97. $client = Passport::client()->forceFill([
  98. 'user_id' => null,
  99. 'name' => e($request->client_name),
  100. 'secret' => Str::random(40),
  101. 'redirect' => $uris,
  102. 'personal_access_client' => false,
  103. 'password_client' => false,
  104. 'revoked' => false,
  105. ]);
  106. $client->save();
  107. $res = [
  108. 'id' => $client->id,
  109. 'name' => $client->name,
  110. 'website' => null,
  111. 'redirect_uri' => $client->redirect,
  112. 'client_id' => $client->id,
  113. 'client_secret' => $client->secret,
  114. 'vapid_key' => null
  115. ];
  116. return response()->json($res, 200, [
  117. 'Access-Control-Allow-Origin' => '*'
  118. ]);
  119. }
  120. /**
  121. * GET /api/v1/accounts/verify_credentials
  122. *
  123. *
  124. * @return \App\Transformer\Api\AccountTransformer
  125. */
  126. public function verifyCredentials(Request $request)
  127. {
  128. $user = $request->user();
  129. abort_if(!$user, 403);
  130. abort_if($user->status != null, 403);
  131. $res = AccountService::getMastodon($user->profile_id);
  132. $res['source'] = [
  133. 'privacy' => $res['locked'] ? 'private' : 'public',
  134. 'sensitive' => false,
  135. 'language' => $user->language ?? 'en',
  136. 'note' => '',
  137. 'fields' => []
  138. ];
  139. return response()->json($res);
  140. }
  141. /**
  142. * GET /api/v1/accounts/{id}
  143. *
  144. * @param integer $id
  145. *
  146. * @return \App\Transformer\Api\AccountTransformer
  147. */
  148. public function accountById(Request $request, $id)
  149. {
  150. $res = AccountService::getMastodon($id, true);
  151. if(!$res) {
  152. return response()->json(['error' => 'Record not found'], 404);
  153. }
  154. return response()->json($res);
  155. }
  156. /**
  157. * PATCH /api/v1/accounts/update_credentials
  158. *
  159. * @return \App\Transformer\Api\AccountTransformer
  160. */
  161. public function accountUpdateCredentials(Request $request)
  162. {
  163. abort_if(!$request->user(), 403);
  164. $this->validate($request, [
  165. 'avatar' => 'sometimes|mimetypes:image/jpeg,image/png|min:10|max:' . config('pixelfed.max_avatar_size'),
  166. 'display_name' => 'nullable|string',
  167. 'note' => 'nullable|string',
  168. 'locked' => 'nullable',
  169. 'website' => 'nullable',
  170. // 'source.privacy' => 'nullable|in:unlisted,public,private',
  171. // 'source.sensitive' => 'nullable|boolean'
  172. ], [
  173. 'required' => 'The :attribute field is required.',
  174. 'avatar.mimetypes' => 'The file must be in jpeg or png format',
  175. 'avatar.max' => 'The :attribute exceeds the file size limit of ' . PrettyNumber::size(config('pixelfed.max_avatar_size'), true, false),
  176. ]);
  177. $user = $request->user();
  178. $profile = $user->profile;
  179. $settings = $user->settings;
  180. $changes = false;
  181. $other = array_merge(AccountService::defaultSettings()['other'], $settings->other ?? []);
  182. $syncLicenses = false;
  183. $licenseChanged = false;
  184. $composeSettings = array_merge(AccountService::defaultSettings()['compose_settings'], $settings->compose_settings ?? []);
  185. if($request->has('avatar')) {
  186. $av = Avatar::whereProfileId($profile->id)->first();
  187. if($av) {
  188. $currentAvatar = storage_path('app/'.$av->media_path);
  189. $file = $request->file('avatar');
  190. $path = "public/avatars/{$profile->id}";
  191. $name = strtolower(str_random(6)). '.' . $file->guessExtension();
  192. $request->file('avatar')->storeAs($path, $name);
  193. $av->media_path = "{$path}/{$name}";
  194. $av->save();
  195. Cache::forget("avatar:{$profile->id}");
  196. Cache::forget('user:account:id:'.$user->id);
  197. AvatarOptimize::dispatch($user->profile, $currentAvatar);
  198. }
  199. $changes = true;
  200. }
  201. if($request->has('source[language]')) {
  202. $lang = $request->input('source[language]');
  203. if(in_array($lang, Localization::languages())) {
  204. $user->language = $lang;
  205. $changes = true;
  206. $other['language'] = $lang;
  207. }
  208. }
  209. if($request->has('website')) {
  210. $website = $request->input('website');
  211. if($website != $profile->website) {
  212. if($website) {
  213. if(!strpos($website, '.')) {
  214. $website = null;
  215. }
  216. if($website && !strpos($website, '://')) {
  217. $website = 'https://' . $website;
  218. }
  219. $host = parse_url($website, PHP_URL_HOST);
  220. $bannedInstances = InstanceService::getBannedDomains();
  221. if(in_array($host, $bannedInstances)) {
  222. $website = null;
  223. }
  224. }
  225. $profile->website = $website ? $website : null;
  226. $changes = true;
  227. }
  228. }
  229. if($request->has('display_name')) {
  230. $displayName = $request->input('display_name');
  231. if($displayName !== $user->name) {
  232. $user->name = $displayName;
  233. $profile->name = $displayName;
  234. $changes = true;
  235. }
  236. }
  237. if($request->has('note')) {
  238. $note = $request->input('note');
  239. if($note !== strip_tags($profile->bio)) {
  240. $profile->bio = Autolink::create()->autolink(strip_tags($note));
  241. $changes = true;
  242. }
  243. }
  244. if($request->has('locked')) {
  245. $locked = $request->input('locked') == 'true';
  246. if($profile->is_private != $locked) {
  247. $profile->is_private = $locked;
  248. $changes = true;
  249. }
  250. }
  251. if($request->has('reduce_motion')) {
  252. $reduced = $request->input('reduce_motion');
  253. if($settings->reduce_motion != $reduced) {
  254. $settings->reduce_motion = $reduced;
  255. $changes = true;
  256. }
  257. }
  258. if($request->has('high_contrast_mode')) {
  259. $contrast = $request->input('high_contrast_mode');
  260. if($settings->high_contrast_mode != $contrast) {
  261. $settings->high_contrast_mode = $contrast;
  262. $changes = true;
  263. }
  264. }
  265. if($request->has('video_autoplay')) {
  266. $autoplay = $request->input('video_autoplay');
  267. if($settings->video_autoplay != $autoplay) {
  268. $settings->video_autoplay = $autoplay;
  269. $changes = true;
  270. }
  271. }
  272. if($request->has('license')) {
  273. $license = $request->input('license');
  274. abort_if(!in_array($license, License::keys()), 422, 'Invalid media license id');
  275. $syncLicenses = $request->input('sync_licenses') == true;
  276. abort_if($syncLicenses && Cache::get('pf:settings:mls_recently:'.$user->id) == 2, 422, 'You can only sync licenses twice per 24 hours');
  277. if($composeSettings['default_license'] != $license) {
  278. $composeSettings['default_license'] = $license;
  279. $licenseChanged = true;
  280. $changes = true;
  281. }
  282. }
  283. if($request->has('media_descriptions')) {
  284. $md = $request->input('media_descriptions') == true;
  285. if($composeSettings['media_descriptions'] != $md) {
  286. $composeSettings['media_descriptions'] = $md;
  287. $changes = true;
  288. }
  289. }
  290. if($request->has('crawlable')) {
  291. $crawlable = $request->input('crawlable');
  292. if($settings->crawlable != $crawlable) {
  293. $settings->crawlable = $crawlable;
  294. $changes = true;
  295. }
  296. }
  297. if($request->has('show_profile_follower_count')) {
  298. $show_profile_follower_count = $request->input('show_profile_follower_count');
  299. if($settings->show_profile_follower_count != $show_profile_follower_count) {
  300. $settings->show_profile_follower_count = $show_profile_follower_count;
  301. $changes = true;
  302. }
  303. }
  304. if($request->has('show_profile_following_count')) {
  305. $show_profile_following_count = $request->input('show_profile_following_count');
  306. if($settings->show_profile_following_count != $show_profile_following_count) {
  307. $settings->show_profile_following_count = $show_profile_following_count;
  308. $changes = true;
  309. }
  310. }
  311. if($request->has('public_dm')) {
  312. $public_dm = $request->input('public_dm');
  313. if($settings->public_dm != $public_dm) {
  314. $settings->public_dm = $public_dm;
  315. $changes = true;
  316. }
  317. }
  318. if($request->has('source[privacy]')) {
  319. $scope = $request->input('source[privacy]');
  320. if(in_array($scope, ['public', 'private', 'unlisted'])) {
  321. if($composeSettings['default_scope'] != $scope) {
  322. $composeSettings['default_scope'] = $profile->is_private ? 'private' : $scope;
  323. $changes = true;
  324. }
  325. }
  326. }
  327. if($request->has('disable_embeds')) {
  328. $disabledEmbeds = $request->input('disable_embeds');
  329. if($other['disable_embeds'] != $disabledEmbeds) {
  330. $other['disable_embeds'] = $disabledEmbeds;
  331. $changes = true;
  332. }
  333. }
  334. if($changes) {
  335. $settings->other = $other;
  336. $settings->compose_settings = $composeSettings;
  337. $settings->save();
  338. $user->save();
  339. $profile->save();
  340. Cache::forget('profile:settings:' . $profile->id);
  341. Cache::forget('user:account:id:' . $profile->user_id);
  342. Cache::forget('profile:follower_count:' . $profile->id);
  343. Cache::forget('profile:following_count:' . $profile->id);
  344. Cache::forget('profile:embed:' . $profile->id);
  345. Cache::forget('profile:compose:settings:' . $user->id);
  346. Cache::forget('profile:view:'.$user->username);
  347. AccountService::del($user->profile_id);
  348. }
  349. if($syncLicenses && $licenseChanged) {
  350. $key = 'pf:settings:mls_recently:'.$user->id;
  351. $val = Cache::has($key) ? 2 : 1;
  352. Cache::put($key, $val, 86400);
  353. MediaSyncLicensePipeline::dispatch($user->id, $request->input('license'));
  354. }
  355. $res = AccountService::getMastodon($user->profile_id);
  356. $res['bio'] = strip_tags($res['note']);
  357. $res = array_merge($res, $other);
  358. return response()->json($res);
  359. }
  360. /**
  361. * GET /api/v1/accounts/{id}/followers
  362. *
  363. * @param integer $id
  364. *
  365. * @return \App\Transformer\Api\AccountTransformer
  366. */
  367. public function accountFollowersById(Request $request, $id)
  368. {
  369. abort_if(!$request->user(), 403);
  370. $account = AccountService::get($id);
  371. abort_if(!$account, 404);
  372. $pid = $request->user()->profile_id;
  373. if($pid != $account['id']) {
  374. if($account['locked']) {
  375. if(FollowerService::follows($pid, $account['id'])) {
  376. return [];
  377. }
  378. }
  379. if(AccountService::hiddenFollowers($id)) {
  380. return [];
  381. }
  382. if($request->has('page') && $request->page >= 5) {
  383. return [];
  384. }
  385. }
  386. $res = DB::table('followers')
  387. ->select('id', 'profile_id', 'following_id')
  388. ->whereFollowingId($account['id'])
  389. ->orderByDesc('id')
  390. ->simplePaginate(10)
  391. ->map(function($follower) {
  392. return AccountService::getMastodon($follower->profile_id);
  393. })
  394. ->filter(function($account) {
  395. return $account && isset($account['id']);
  396. })
  397. ->values()
  398. ->toArray();
  399. return response()->json($res);
  400. }
  401. /**
  402. * GET /api/v1/accounts/{id}/following
  403. *
  404. * @param integer $id
  405. *
  406. * @return \App\Transformer\Api\AccountTransformer
  407. */
  408. public function accountFollowingById(Request $request, $id)
  409. {
  410. abort_if(!$request->user(), 403);
  411. $account = AccountService::get($id);
  412. abort_if(!$account, 404);
  413. $pid = $request->user()->profile_id;
  414. if($pid != $account['id']) {
  415. if($account['locked']) {
  416. if(FollowerService::follows($pid, $account['id'])) {
  417. return [];
  418. }
  419. }
  420. if(AccountService::hiddenFollowing($id)) {
  421. return [];
  422. }
  423. if($request->has('page') && $request->page >= 5) {
  424. return [];
  425. }
  426. }
  427. $res = DB::table('followers')
  428. ->select('id', 'profile_id', 'following_id')
  429. ->whereProfileId($account['id'])
  430. ->orderByDesc('id')
  431. ->simplePaginate(10)
  432. ->map(function($follower) {
  433. return AccountService::get($follower->following_id);
  434. })
  435. ->filter(function($account) {
  436. return $account && isset($account['id']);
  437. })
  438. ->values()
  439. ->toArray();
  440. return response()->json($res);
  441. }
  442. /**
  443. * GET /api/v1/accounts/{id}/statuses
  444. *
  445. * @param integer $id
  446. *
  447. * @return \App\Transformer\Api\StatusTransformer
  448. */
  449. public function accountStatusesById(Request $request, $id)
  450. {
  451. $user = $request->user();
  452. $this->validate($request, [
  453. 'only_media' => 'nullable',
  454. 'media_type' => 'sometimes|string|in:photo,video',
  455. 'pinned' => 'nullable',
  456. 'exclude_replies' => 'nullable',
  457. 'max_id' => 'nullable|integer|min:0|max:' . PHP_INT_MAX,
  458. 'since_id' => 'nullable|integer|min:0|max:' . PHP_INT_MAX,
  459. 'min_id' => 'nullable|integer|min:0|max:' . PHP_INT_MAX,
  460. 'limit' => 'nullable|integer|min:1|max:80'
  461. ]);
  462. $profile = AccountService::getMastodon($id);
  463. abort_if(!$profile, 404);
  464. $limit = $request->limit ?? 20;
  465. $max_id = $request->max_id;
  466. $min_id = $request->min_id;
  467. if(!$max_id && !$min_id) {
  468. $min_id = 1;
  469. }
  470. $pid = $request->user()->profile_id;
  471. $scope = $request->only_media == true ?
  472. ['photo', 'photo:album', 'video', 'video:album'] :
  473. ['photo', 'photo:album', 'video', 'video:album', 'share', 'reply'];
  474. if($request->only_media && $request->has('media_type')) {
  475. $mt = $request->input('media_type');
  476. if($mt == 'video') {
  477. $scope = ['video', 'video:album'];
  478. }
  479. }
  480. if($pid == $profile['id']) {
  481. $visibility = ['public', 'unlisted', 'private'];
  482. } else if($profile['locked']) {
  483. $following = FollowerService::follows($pid, $profile['id']);
  484. abort_unless($following, 403);
  485. $visibility = ['public', 'unlisted', 'private'];
  486. } else {
  487. $following = FollowerService::follows($pid, $profile['id']);
  488. $visibility = $following ? ['public', 'unlisted', 'private'] : ['public', 'unlisted'];
  489. }
  490. $dir = $min_id ? '>' : '<';
  491. $id = $min_id ?? $max_id;
  492. $res = Status::whereProfileId($profile['id'])
  493. ->whereNull('in_reply_to_id')
  494. ->whereNull('reblog_of_id')
  495. ->whereIn('type', $scope)
  496. ->where('id', $dir, $id)
  497. ->whereIn('scope', $visibility)
  498. ->limit($limit)
  499. ->orderByDesc('id')
  500. ->get()
  501. ->map(function($s) use($user) {
  502. try {
  503. $status = StatusService::getMastodon($s->id, false);
  504. } catch (\Exception $e) {
  505. $status = false;
  506. }
  507. if($user && $status) {
  508. $status['favourited'] = (bool) LikeService::liked($user->profile_id, $s->id);
  509. }
  510. return $status;
  511. })
  512. ->filter(function($s) {
  513. return $s;
  514. })
  515. ->values();
  516. return response()->json($res);
  517. }
  518. /**
  519. * POST /api/v1/accounts/{id}/follow
  520. *
  521. * @param integer $id
  522. *
  523. * @return \App\Transformer\Api\RelationshipTransformer
  524. */
  525. public function accountFollowById(Request $request, $id)
  526. {
  527. abort_if(!$request->user(), 403);
  528. $user = $request->user();
  529. $target = Profile::where('id', '!=', $user->profile_id)
  530. ->whereNull('status')
  531. ->findOrFail($id);
  532. $private = (bool) $target->is_private;
  533. $remote = (bool) $target->domain;
  534. $blocked = UserFilter::whereUserId($target->id)
  535. ->whereFilterType('block')
  536. ->whereFilterableId($user->profile_id)
  537. ->whereFilterableType('App\Profile')
  538. ->exists();
  539. if($blocked == true) {
  540. abort(400, 'You cannot follow this user.');
  541. }
  542. $isFollowing = Follower::whereProfileId($user->profile_id)
  543. ->whereFollowingId($target->id)
  544. ->exists();
  545. // Following already, return empty relationship
  546. if($isFollowing == true) {
  547. $res = RelationshipService::get($user->profile_id, $target->id) ?? [];
  548. return response()->json($res);
  549. }
  550. // Rate limits, max 7500 followers per account
  551. if($user->profile->following()->count() >= Follower::MAX_FOLLOWING) {
  552. abort(400, 'You cannot follow more than ' . Follower::MAX_FOLLOWING . ' accounts');
  553. }
  554. // Rate limits, follow 30 accounts per hour max
  555. if($user->profile->following()->where('followers.created_at', '>', now()->subHour())->count() >= Follower::FOLLOW_PER_HOUR) {
  556. abort(400, 'You can only follow ' . Follower::FOLLOW_PER_HOUR . ' users per hour');
  557. }
  558. if($private == true) {
  559. $follow = FollowRequest::firstOrCreate([
  560. 'follower_id' => $user->profile_id,
  561. 'following_id' => $target->id
  562. ]);
  563. if($remote == true && config('federation.activitypub.remoteFollow') == true) {
  564. (new FollowerController())->sendFollow($user->profile, $target);
  565. }
  566. } else {
  567. $follower = new Follower();
  568. $follower->profile_id = $user->profile_id;
  569. $follower->following_id = $target->id;
  570. $follower->save();
  571. if($remote == true && config('federation.activitypub.remoteFollow') == true) {
  572. (new FollowerController())->sendFollow($user->profile, $target);
  573. }
  574. FollowPipeline::dispatch($follower);
  575. }
  576. RelationshipService::refresh($user->profile_id, $target->id);
  577. Cache::forget('profile:following:'.$target->id);
  578. Cache::forget('profile:followers:'.$target->id);
  579. Cache::forget('profile:following:'.$user->profile_id);
  580. Cache::forget('profile:followers:'.$user->profile_id);
  581. Cache::forget('api:local:exp:rec:'.$user->profile_id);
  582. Cache::forget('user:account:id:'.$target->user_id);
  583. Cache::forget('user:account:id:'.$user->id);
  584. Cache::forget('profile:follower_count:'.$target->id);
  585. Cache::forget('profile:follower_count:'.$user->profile_id);
  586. Cache::forget('profile:following_count:'.$target->id);
  587. Cache::forget('profile:following_count:'.$user->profile_id);
  588. AccountService::del($user->profile_id);
  589. AccountService::del($target->id);
  590. $res = RelationshipService::get($user->profile_id, $target->id);
  591. return response()->json($res);
  592. }
  593. /**
  594. * POST /api/v1/accounts/{id}/unfollow
  595. *
  596. * @param integer $id
  597. *
  598. * @return \App\Transformer\Api\RelationshipTransformer
  599. */
  600. public function accountUnfollowById(Request $request, $id)
  601. {
  602. abort_if(!$request->user(), 403);
  603. $user = $request->user();
  604. $target = Profile::where('id', '!=', $user->profile_id)
  605. ->whereNull('status')
  606. ->findOrFail($id);
  607. $private = (bool) $target->is_private;
  608. $remote = (bool) $target->domain;
  609. $isFollowing = Follower::whereProfileId($user->profile_id)
  610. ->whereFollowingId($target->id)
  611. ->exists();
  612. if($isFollowing == false) {
  613. $resource = new Fractal\Resource\Item($target, new RelationshipTransformer());
  614. $res = $this->fractal->createData($resource)->toArray();
  615. return response()->json($res);
  616. }
  617. // Rate limits, follow 30 accounts per hour max
  618. if($user->profile->following()->where('followers.updated_at', '>', now()->subHour())->count() >= Follower::FOLLOW_PER_HOUR) {
  619. abort(400, 'You can only follow or unfollow ' . Follower::FOLLOW_PER_HOUR . ' users per hour');
  620. }
  621. $user->profile->decrement('following_count');
  622. FollowRequest::whereFollowerId($user->profile_id)
  623. ->whereFollowingId($target->id)
  624. ->delete();
  625. Follower::whereProfileId($user->profile_id)
  626. ->whereFollowingId($target->id)
  627. ->delete();
  628. if($remote == true && config('federation.activitypub.remoteFollow') == true) {
  629. (new FollowerController())->sendUndoFollow($user->profile, $target);
  630. }
  631. RelationshipService::refresh($user->profile_id, $target->id);
  632. Cache::forget('profile:following:'.$target->id);
  633. Cache::forget('profile:followers:'.$target->id);
  634. Cache::forget('profile:following:'.$user->profile_id);
  635. Cache::forget('profile:followers:'.$user->profile_id);
  636. Cache::forget('api:local:exp:rec:'.$user->profile_id);
  637. Cache::forget('user:account:id:'.$target->user_id);
  638. Cache::forget('user:account:id:'.$user->id);
  639. Cache::forget('profile:follower_count:'.$target->id);
  640. Cache::forget('profile:follower_count:'.$user->profile_id);
  641. Cache::forget('profile:following_count:'.$target->id);
  642. Cache::forget('profile:following_count:'.$user->profile_id);
  643. AccountService::del($user->profile_id);
  644. AccountService::del($target->id);
  645. $res = RelationshipService::get($user->profile_id, $target->id);
  646. return response()->json($res);
  647. }
  648. /**
  649. * GET /api/v1/accounts/relationships
  650. *
  651. * @param array|integer $id
  652. *
  653. * @return \App\Services\RelationshipService
  654. */
  655. public function accountRelationshipsById(Request $request)
  656. {
  657. abort_if(!$request->user(), 403);
  658. $this->validate($request, [
  659. 'id' => 'required|array|min:1|max:20',
  660. 'id.*' => 'required|integer|min:1|max:' . PHP_INT_MAX
  661. ]);
  662. $pid = $request->user()->profile_id ?? $request->user()->profile->id;
  663. $res = collect($request->input('id'))
  664. ->filter(function($id) use($pid) {
  665. return $id != $pid;
  666. })
  667. ->map(function($id) use($pid) {
  668. return RelationshipService::get($pid, $id);
  669. });
  670. return response()->json($res);
  671. }
  672. /**
  673. * GET /api/v1/accounts/search
  674. *
  675. *
  676. *
  677. * @return \App\Transformer\Api\AccountTransformer
  678. */
  679. public function accountSearch(Request $request)
  680. {
  681. abort_if(!$request->user(), 403);
  682. $this->validate($request, [
  683. 'q' => 'required|string|min:1|max:255',
  684. 'limit' => 'nullable|integer|min:1|max:40',
  685. 'resolve' => 'nullable'
  686. ]);
  687. $user = $request->user();
  688. $query = $request->input('q');
  689. $limit = $request->input('limit') ?? 20;
  690. $resolve = (bool) $request->input('resolve', false);
  691. $q = '%' . $query . '%';
  692. $profiles = Profile::whereNull('status')
  693. ->where('username', 'like', $q)
  694. ->orWhere('name', 'like', $q)
  695. ->limit($limit)
  696. ->get();
  697. $resource = new Fractal\Resource\Collection($profiles, new AccountTransformer());
  698. $res = $this->fractal->createData($resource)->toArray();
  699. return response()->json($res);
  700. }
  701. /**
  702. * GET /api/v1/blocks
  703. *
  704. *
  705. *
  706. * @return \App\Transformer\Api\AccountTransformer
  707. */
  708. public function accountBlocks(Request $request)
  709. {
  710. abort_if(!$request->user(), 403);
  711. $this->validate($request, [
  712. 'limit' => 'nullable|integer|min:1|max:40',
  713. 'page' => 'nullable|integer|min:1|max:10'
  714. ]);
  715. $user = $request->user();
  716. $limit = $request->input('limit') ?? 40;
  717. $blocked = UserFilter::select('filterable_id','filterable_type','filter_type','user_id')
  718. ->whereUserId($user->profile_id)
  719. ->whereFilterableType('App\Profile')
  720. ->whereFilterType('block')
  721. ->simplePaginate($limit)
  722. ->pluck('filterable_id');
  723. $profiles = Profile::findOrFail($blocked);
  724. $resource = new Fractal\Resource\Collection($profiles, new AccountTransformer());
  725. $res = $this->fractal->createData($resource)->toArray();
  726. return response()->json($res);
  727. }
  728. /**
  729. * POST /api/v1/accounts/{id}/block
  730. *
  731. * @param integer $id
  732. *
  733. * @return \App\Transformer\Api\RelationshipTransformer
  734. */
  735. public function accountBlockById(Request $request, $id)
  736. {
  737. abort_if(!$request->user(), 403);
  738. $user = $request->user();
  739. $pid = $user->profile_id ?? $user->profile->id;
  740. if($id == $pid) {
  741. abort(400, 'You cannot block yourself');
  742. }
  743. $profile = Profile::findOrFail($id);
  744. if($profile->user->is_admin == true) {
  745. abort(400, 'You cannot block an admin');
  746. }
  747. Follower::whereProfileId($profile->id)->whereFollowingId($pid)->delete();
  748. Follower::whereProfileId($pid)->whereFollowingId($profile->id)->delete();
  749. Notification::whereProfileId($pid)->whereActorId($profile->id)->delete();
  750. $filter = UserFilter::firstOrCreate([
  751. 'user_id' => $pid,
  752. 'filterable_id' => $profile->id,
  753. 'filterable_type' => 'App\Profile',
  754. 'filter_type' => 'block',
  755. ]);
  756. Cache::forget("user:filter:list:$pid");
  757. Cache::forget("api:local:exp:rec:$pid");
  758. $resource = new Fractal\Resource\Item($profile, new RelationshipTransformer());
  759. $res = $this->fractal->createData($resource)->toArray();
  760. return response()->json($res);
  761. }
  762. /**
  763. * POST /api/v1/accounts/{id}/unblock
  764. *
  765. * @param integer $id
  766. *
  767. * @return \App\Transformer\Api\RelationshipTransformer
  768. */
  769. public function accountUnblockById(Request $request, $id)
  770. {
  771. abort_if(!$request->user(), 403);
  772. $user = $request->user();
  773. $pid = $user->profile_id ?? $user->profile->id;
  774. if($id == $pid) {
  775. abort(400, 'You cannot unblock yourself');
  776. }
  777. $profile = Profile::findOrFail($id);
  778. UserFilter::whereUserId($pid)
  779. ->whereFilterableId($profile->id)
  780. ->whereFilterableType('App\Profile')
  781. ->whereFilterType('block')
  782. ->delete();
  783. Cache::forget("user:filter:list:$pid");
  784. Cache::forget("api:local:exp:rec:$pid");
  785. $resource = new Fractal\Resource\Item($profile, new RelationshipTransformer());
  786. $res = $this->fractal->createData($resource)->toArray();
  787. return response()->json($res);
  788. }
  789. /**
  790. * GET /api/v1/custom_emojis
  791. *
  792. * Return empty array, we don't support custom emoji
  793. *
  794. * @return array
  795. */
  796. public function customEmojis()
  797. {
  798. return response(CustomEmojiService::all())->header('Content-Type', 'application/json');
  799. }
  800. /**
  801. * GET /api/v1/domain_blocks
  802. *
  803. * Return empty array
  804. *
  805. * @return array
  806. */
  807. public function accountDomainBlocks(Request $request)
  808. {
  809. abort_if(!$request->user(), 403);
  810. return response()->json([]);
  811. }
  812. /**
  813. * GET /api/v1/endorsements
  814. *
  815. * Return empty array
  816. *
  817. * @return array
  818. */
  819. public function accountEndorsements(Request $request)
  820. {
  821. abort_if(!$request->user(), 403);
  822. return response()->json([]);
  823. }
  824. /**
  825. * GET /api/v1/favourites
  826. *
  827. * Returns collection of liked statuses
  828. *
  829. * @return \App\Transformer\Api\StatusTransformer
  830. */
  831. public function accountFavourites(Request $request)
  832. {
  833. abort_if(!$request->user(), 403);
  834. $this->validate($request, [
  835. 'limit' => 'sometimes|integer|min:1|max:20'
  836. ]);
  837. $user = $request->user();
  838. $maxId = $request->input('max_id');
  839. $minId = $request->input('min_id');
  840. $limit = $request->input('limit') ?? 10;
  841. $res = Like::whereProfileId($user->profile_id)
  842. ->when($maxId, function($q, $maxId) {
  843. return $q->where('id', '<', $maxId);
  844. })
  845. ->when($minId, function($q, $minId) {
  846. return $q->where('id', '>', $minId);
  847. })
  848. ->orderByDesc('id')
  849. ->limit($limit)
  850. ->get()
  851. ->map(function($like) {
  852. $status = StatusService::getMastodon($like['status_id'], false);
  853. $status['like_id'] = $like->id;
  854. $status['liked_at'] = $like->created_at->format('c');
  855. return $status;
  856. })
  857. ->filter(function($status) {
  858. return $status && isset($status['id'], $status['like_id']);
  859. })
  860. ->values();
  861. if($res->count()) {
  862. $ids = $res->map(function($status) {
  863. return $status['like_id'];
  864. });
  865. $max = $ids->max();
  866. $min = $ids->min();
  867. $baseUrl = config('app.url') . '/api/v1/favourites?limit=' . $limit . '&';
  868. $link = '<'.$baseUrl.'max_id='.$max.'>; rel="next",<'.$baseUrl.'min_id='.$min.'>; rel="prev"';
  869. return response()
  870. ->json($res)
  871. ->withHeaders([
  872. 'Link' => $link,
  873. ]);
  874. } else {
  875. return response()->json($res);
  876. }
  877. }
  878. /**
  879. * POST /api/v1/statuses/{id}/favourite
  880. *
  881. * @param integer $id
  882. *
  883. * @return \App\Transformer\Api\StatusTransformer
  884. */
  885. public function statusFavouriteById(Request $request, $id)
  886. {
  887. abort_if(!$request->user(), 403);
  888. $user = $request->user();
  889. $status = StatusService::getMastodon($id, false);
  890. abort_unless($status, 400);
  891. $spid = $status['account']['id'];
  892. if($spid !== $user->profile_id) {
  893. if($status['visibility'] == 'private') {
  894. abort_if(!FollowerService::follows($user->profile_id, $spid), 403);
  895. } else {
  896. abort_if(!in_array($status['visibility'], ['public','unlisted']), 403);
  897. }
  898. }
  899. $like = Like::firstOrCreate([
  900. 'profile_id' => $user->profile_id,
  901. 'status_id' => $status['id']
  902. ]);
  903. if($like->wasRecentlyCreated == true) {
  904. $like->status_profile_id = $spid;
  905. $like->is_comment = !empty($status['in_reply_to_id']);
  906. $like->save();
  907. Status::findOrFail($status['id'])->update([
  908. 'favourites_count' => ($status['favourites_count'] ?? 0) + 1
  909. ]);
  910. LikePipeline::dispatch($like);
  911. }
  912. $status['favourited'] = true;
  913. $status['favourites_count'] = $status['favourites_count'] + 1;
  914. return response()->json($status);
  915. }
  916. /**
  917. * POST /api/v1/statuses/{id}/unfavourite
  918. *
  919. * @param integer $id
  920. *
  921. * @return \App\Transformer\Api\StatusTransformer
  922. */
  923. public function statusUnfavouriteById(Request $request, $id)
  924. {
  925. abort_if(!$request->user(), 403);
  926. $user = $request->user();
  927. $status = Status::findOrFail($id);
  928. if($status->profile_id !== $user->profile_id) {
  929. if($status->scope == 'private') {
  930. abort_if(!$status->profile->followedBy($user->profile), 403);
  931. } else {
  932. abort_if(!in_array($status->scope, ['public','unlisted']), 403);
  933. }
  934. }
  935. $like = Like::whereProfileId($user->profile_id)
  936. ->whereStatusId($status->id)
  937. ->first();
  938. if($like) {
  939. $like->forceDelete();
  940. $status->likes_count = $status->likes()->count();
  941. $status->save();
  942. }
  943. StatusService::del($status->id);
  944. $res = StatusService::getMastodon($status->id, false);
  945. $res['favourited'] = false;
  946. return response()->json($res);
  947. }
  948. /**
  949. * GET /api/v1/filters
  950. *
  951. * Return empty response since we filter server side
  952. *
  953. * @return array
  954. */
  955. public function accountFilters(Request $request)
  956. {
  957. abort_if(!$request->user(), 403);
  958. return response()->json([]);
  959. }
  960. /**
  961. * GET /api/v1/follow_requests
  962. *
  963. * Return array of Accounts that have sent follow requests
  964. *
  965. * @return \App\Transformer\Api\AccountTransformer
  966. */
  967. public function accountFollowRequests(Request $request)
  968. {
  969. abort_if(!$request->user(), 403);
  970. $user = $request->user();
  971. $followRequests = FollowRequest::whereFollowingId($user->profile->id)->pluck('follower_id');
  972. $profiles = Profile::find($followRequests);
  973. $resource = new Fractal\Resource\Collection($profiles, new AccountTransformer());
  974. $res = $this->fractal->createData($resource)->toArray();
  975. return response()->json($res);
  976. }
  977. /**
  978. * POST /api/v1/follow_requests/{id}/authorize
  979. *
  980. * @param integer $id
  981. *
  982. * @return null
  983. */
  984. public function accountFollowRequestAccept(Request $request, $id)
  985. {
  986. abort_if(!$request->user(), 403);
  987. // todo
  988. return response()->json([]);
  989. }
  990. /**
  991. * POST /api/v1/follow_requests/{id}/reject
  992. *
  993. * @param integer $id
  994. *
  995. * @return null
  996. */
  997. public function accountFollowRequestReject(Request $request, $id)
  998. {
  999. abort_if(!$request->user(), 403);
  1000. // todo
  1001. return response()->json([]);
  1002. }
  1003. /**
  1004. * GET /api/v1/suggestions
  1005. *
  1006. * Return empty array as we don't support suggestions
  1007. *
  1008. * @return null
  1009. */
  1010. public function accountSuggestions(Request $request)
  1011. {
  1012. abort_if(!$request->user(), 403);
  1013. // todo
  1014. return response()->json([]);
  1015. }
  1016. /**
  1017. * GET /api/v1/instance
  1018. *
  1019. * Information about the server.
  1020. *
  1021. * @return Instance
  1022. */
  1023. public function instance(Request $request)
  1024. {
  1025. $res = Cache::remember('api:v1:instance-data-response-v0', 1800, function () {
  1026. $contact = Cache::remember('api:v1:instance-data:contact', 604800, function () {
  1027. $admin = User::whereIsAdmin(true)->first();
  1028. return $admin && isset($admin->profile_id) ?
  1029. AccountService::getMastodon($admin->profile_id, true) :
  1030. null;
  1031. });
  1032. $stats = Cache::remember('api:v1:instance-data:stats', 43200, function () {
  1033. return [
  1034. 'user_count' => User::count(),
  1035. 'status_count' => Status::whereNull('uri')->count(),
  1036. 'domain_count' => Instance::count(),
  1037. ];
  1038. });
  1039. $rules = Cache::remember('api:v1:instance-data:rules', 604800, function () {
  1040. return config_cache('app.rules') ?
  1041. collect(json_decode(config_cache('app.rules'), true))
  1042. ->map(function($rule, $key) {
  1043. $id = $key + 1;
  1044. return [
  1045. 'id' => "{$id}",
  1046. 'text' => $rule
  1047. ];
  1048. })
  1049. ->toArray() : [];
  1050. });
  1051. return [
  1052. 'uri' => config('pixelfed.domain.app'),
  1053. 'title' => config('app.name'),
  1054. 'short_description' => 'Pixelfed is an image sharing platform, an ethical alternative to centralized platforms',
  1055. 'description' => 'Pixelfed is an image sharing platform, an ethical alternative to centralized platforms',
  1056. 'email' => config('instance.email'),
  1057. 'version' => '2.7.2 (compatible; Pixelfed ' . config('pixelfed.version') .')',
  1058. 'urls' => [],
  1059. 'stats' => $stats,
  1060. 'thumbnail' => url('headers/default.jpg'),
  1061. 'languages' => ['en'],
  1062. 'registrations' => (bool) config('pixelfed.open_registration'),
  1063. 'approval_required' => false,
  1064. 'contact_account' => $contact,
  1065. 'rules' => $rules
  1066. ];
  1067. });
  1068. return response()->json($res);
  1069. }
  1070. /**
  1071. * GET /api/v1/lists
  1072. *
  1073. * Return empty array as we don't support lists
  1074. *
  1075. * @return null
  1076. */
  1077. public function accountLists(Request $request)
  1078. {
  1079. abort_if(!$request->user(), 403);
  1080. return response()->json([]);
  1081. }
  1082. /**
  1083. * GET /api/v1/accounts/{id}/lists
  1084. *
  1085. * @param integer $id
  1086. *
  1087. * @return null
  1088. */
  1089. public function accountListsById(Request $request, $id)
  1090. {
  1091. abort_if(!$request->user(), 403);
  1092. return response()->json([]);
  1093. }
  1094. /**
  1095. * POST /api/v1/media
  1096. *
  1097. *
  1098. * @return MediaTransformer
  1099. */
  1100. public function mediaUpload(Request $request)
  1101. {
  1102. abort_if(!$request->user(), 403);
  1103. $this->validate($request, [
  1104. 'file.*' => function() {
  1105. return [
  1106. 'required',
  1107. 'mimetypes:' . config_cache('pixelfed.media_types'),
  1108. 'max:' . config_cache('pixelfed.max_photo_size'),
  1109. ];
  1110. },
  1111. 'filter_name' => 'nullable|string|max:24',
  1112. 'filter_class' => 'nullable|alpha_dash|max:24',
  1113. 'description' => 'nullable|string|max:' . config_cache('pixelfed.max_altext_length')
  1114. ]);
  1115. $user = $request->user();
  1116. if($user->last_active_at == null) {
  1117. return [];
  1118. }
  1119. $limitKey = 'compose:rate-limit:media-upload:' . $user->id;
  1120. $limitTtl = now()->addMinutes(15);
  1121. $limitReached = Cache::remember($limitKey, $limitTtl, function() use($user) {
  1122. $dailyLimit = Media::whereUserId($user->id)->where('created_at', '>', now()->subDays(1))->count();
  1123. return $dailyLimit >= 250;
  1124. });
  1125. abort_if($limitReached == true, 429);
  1126. $profile = $user->profile;
  1127. if(config_cache('pixelfed.enforce_account_limit') == true) {
  1128. $size = Cache::remember($user->storageUsedKey(), now()->addDays(3), function() use($user) {
  1129. return Media::whereUserId($user->id)->sum('size') / 1000;
  1130. });
  1131. $limit = (int) config_cache('pixelfed.max_account_size');
  1132. if ($size >= $limit) {
  1133. abort(403, 'Account size limit reached.');
  1134. }
  1135. }
  1136. $filterClass = in_array($request->input('filter_class'), Filter::classes()) ? $request->input('filter_class') : null;
  1137. $filterName = in_array($request->input('filter_name'), Filter::names()) ? $request->input('filter_name') : null;
  1138. $photo = $request->file('file');
  1139. $mimes = explode(',', config_cache('pixelfed.media_types'));
  1140. if(in_array($photo->getMimeType(), $mimes) == false) {
  1141. abort(403, 'Invalid or unsupported mime type.');
  1142. }
  1143. $storagePath = MediaPathService::get($user, 2);
  1144. $path = $photo->store($storagePath);
  1145. $hash = \hash_file('sha256', $photo);
  1146. $license = null;
  1147. $mime = $photo->getMimeType();
  1148. // if($photo->getMimeType() == 'image/heic') {
  1149. // abort_if(config('image.driver') !== 'imagick', 422, 'Invalid media type');
  1150. // abort_if(!in_array('HEIC', \Imagick::queryformats()), 422, 'Unsupported media type');
  1151. // $oldPath = $path;
  1152. // $path = str_replace('.heic', '.jpg', $path);
  1153. // $mime = 'image/jpeg';
  1154. // \Image::make($photo)->save(storage_path("app/{$path}"));
  1155. // @unlink(storage_path("app/{$oldPath}"));
  1156. // }
  1157. $settings = UserSetting::whereUserId($user->id)->first();
  1158. if($settings && !empty($settings->compose_settings)) {
  1159. $compose = $settings->compose_settings;
  1160. if(isset($compose['default_license']) && $compose['default_license'] != 1) {
  1161. $license = $compose['default_license'];
  1162. }
  1163. }
  1164. abort_if(MediaBlocklistService::exists($hash) == true, 451);
  1165. $media = new Media();
  1166. $media->status_id = null;
  1167. $media->profile_id = $profile->id;
  1168. $media->user_id = $user->id;
  1169. $media->media_path = $path;
  1170. $media->original_sha256 = $hash;
  1171. $media->size = $photo->getSize();
  1172. $media->mime = $mime;
  1173. $media->caption = $request->input('description');
  1174. $media->filter_class = $filterClass;
  1175. $media->filter_name = $filterName;
  1176. if($license) {
  1177. $media->license = $license;
  1178. }
  1179. $media->save();
  1180. switch ($media->mime) {
  1181. case 'image/jpeg':
  1182. case 'image/png':
  1183. ImageOptimize::dispatch($media);
  1184. break;
  1185. case 'video/mp4':
  1186. VideoThumbnail::dispatch($media);
  1187. $preview_url = '/storage/no-preview.png';
  1188. $url = '/storage/no-preview.png';
  1189. break;
  1190. }
  1191. Cache::forget($limitKey);
  1192. $resource = new Fractal\Resource\Item($media, new MediaTransformer());
  1193. $res = $this->fractal->createData($resource)->toArray();
  1194. $res['preview_url'] = $media->url(). '?cb=1&_v=' . time();
  1195. $res['url'] = $media->url(). '?cb=1&_v=' . time();
  1196. return response()->json($res);
  1197. }
  1198. /**
  1199. * PUT /api/v1/media/{id}
  1200. *
  1201. * @param integer $id
  1202. *
  1203. * @return MediaTransformer
  1204. */
  1205. public function mediaUpdate(Request $request, $id)
  1206. {
  1207. abort_if(!$request->user(), 403);
  1208. $this->validate($request, [
  1209. 'description' => 'nullable|string|max:' . config_cache('pixelfed.max_altext_length')
  1210. ]);
  1211. $user = $request->user();
  1212. $media = Media::whereUserId($user->id)
  1213. ->whereNull('status_id')
  1214. ->findOrFail($id);
  1215. $media->caption = $request->input('description');
  1216. $media->save();
  1217. $resource = new Fractal\Resource\Item($media, new MediaTransformer());
  1218. $res = $this->fractal->createData($resource)->toArray();
  1219. $res['preview_url'] = url('/storage/no-preview.png');
  1220. $res['url'] = url('/storage/no-preview.png');
  1221. return response()->json($res);
  1222. }
  1223. /**
  1224. * GET /api/v1/mutes
  1225. *
  1226. *
  1227. * @return AccountTransformer
  1228. */
  1229. public function accountMutes(Request $request)
  1230. {
  1231. abort_if(!$request->user(), 403);
  1232. $this->validate($request, [
  1233. 'limit' => 'nullable|integer|min:1|max:40'
  1234. ]);
  1235. $user = $request->user();
  1236. $limit = $request->input('limit') ?? 40;
  1237. $mutes = UserFilter::whereUserId($user->profile_id)
  1238. ->whereFilterableType('App\Profile')
  1239. ->whereFilterType('mute')
  1240. ->simplePaginate($limit)
  1241. ->pluck('filterable_id');
  1242. $accounts = Profile::find($mutes);
  1243. $resource = new Fractal\Resource\Collection($accounts, new AccountTransformer());
  1244. $res = $this->fractal->createData($resource)->toArray();
  1245. return response()->json($res);
  1246. }
  1247. /**
  1248. * POST /api/v1/accounts/{id}/mute
  1249. *
  1250. * @param integer $id
  1251. *
  1252. * @return RelationshipTransformer
  1253. */
  1254. public function accountMuteById(Request $request, $id)
  1255. {
  1256. abort_if(!$request->user(), 403);
  1257. $user = $request->user();
  1258. $pid = $user->profile_id;
  1259. $account = Profile::findOrFail($id);
  1260. $filter = UserFilter::firstOrCreate([
  1261. 'user_id' => $pid,
  1262. 'filterable_id' => $account->id,
  1263. 'filterable_type' => 'App\Profile',
  1264. 'filter_type' => 'mute',
  1265. ]);
  1266. Cache::forget("user:filter:list:$pid");
  1267. Cache::forget("feature:discover:posts:$pid");
  1268. Cache::forget("api:local:exp:rec:$pid");
  1269. $resource = new Fractal\Resource\Item($account, new RelationshipTransformer());
  1270. $res = $this->fractal->createData($resource)->toArray();
  1271. return response()->json($res);
  1272. }
  1273. /**
  1274. * POST /api/v1/accounts/{id}/unmute
  1275. *
  1276. * @param integer $id
  1277. *
  1278. * @return RelationshipTransformer
  1279. */
  1280. public function accountUnmuteById(Request $request, $id)
  1281. {
  1282. abort_if(!$request->user(), 403);
  1283. $user = $request->user();
  1284. $pid = $user->profile_id;
  1285. $account = Profile::findOrFail($id);
  1286. $filter = UserFilter::whereUserId($pid)
  1287. ->whereFilterableId($account->id)
  1288. ->whereFilterableType('App\Profile')
  1289. ->whereFilterType('mute')
  1290. ->first();
  1291. if($filter) {
  1292. $filter->delete();
  1293. Cache::forget("user:filter:list:$pid");
  1294. Cache::forget("feature:discover:posts:$pid");
  1295. Cache::forget("api:local:exp:rec:$pid");
  1296. }
  1297. $resource = new Fractal\Resource\Item($account, new RelationshipTransformer());
  1298. $res = $this->fractal->createData($resource)->toArray();
  1299. return response()->json($res);
  1300. }
  1301. /**
  1302. * GET /api/v1/notifications
  1303. *
  1304. *
  1305. * @return NotificationTransformer
  1306. */
  1307. public function accountNotifications(Request $request)
  1308. {
  1309. abort_if(!$request->user(), 403);
  1310. $this->validate($request, [
  1311. 'limit' => 'nullable|integer|min:1|max:80',
  1312. 'min_id' => 'nullable|integer|min:1|max:'.PHP_INT_MAX,
  1313. 'max_id' => 'nullable|integer|min:1|max:'.PHP_INT_MAX,
  1314. 'since_id' => 'nullable|integer|min:1|max:'.PHP_INT_MAX,
  1315. ]);
  1316. $pid = $request->user()->profile_id;
  1317. $limit = $request->input('limit', 20);
  1318. $since = $request->input('since_id');
  1319. $min = $request->input('min_id');
  1320. $max = $request->input('max_id');
  1321. if(!$since && !$min && !$max) {
  1322. $min = 1;
  1323. }
  1324. $maxId = null;
  1325. $minId = null;
  1326. if($max) {
  1327. $res = NotificationService::getMax($pid, $max, $limit);
  1328. $ids = NotificationService::getRankedMaxId($pid, $max, $limit);
  1329. if(!empty($ids)) {
  1330. $maxId = max($ids);
  1331. $minId = min($ids);
  1332. }
  1333. } else {
  1334. $res = NotificationService::getMin($pid, $min ?? $since, $limit);
  1335. $ids = NotificationService::getRankedMinId($pid, $min ?? $since, $limit);
  1336. if(!empty($ids)) {
  1337. $maxId = max($ids);
  1338. $minId = min($ids);
  1339. }
  1340. }
  1341. if(empty($res) && !Cache::has('pf:services:notifications:hasSynced:'.$pid)) {
  1342. Cache::put('pf:services:notifications:hasSynced:'.$pid, 1, 1209600);
  1343. NotificationService::warmCache($pid, 400, true);
  1344. }
  1345. $baseUrl = config('app.url') . '/api/v1/notifications?limit=' . $limit . '&';
  1346. if($minId == $maxId) {
  1347. $minId = null;
  1348. }
  1349. if($maxId) {
  1350. $link = '<'.$baseUrl.'max_id='.$maxId.'>; rel="next"';
  1351. }
  1352. if($minId) {
  1353. $link = '<'.$baseUrl.'min_id='.$minId.'>; rel="prev"';
  1354. }
  1355. if($maxId && $minId) {
  1356. $link = '<'.$baseUrl.'max_id='.$maxId.'>; rel="next",<'.$baseUrl.'min_id='.$minId.'>; rel="prev"';
  1357. }
  1358. $res = response()->json($res);
  1359. if(isset($link)) {
  1360. $res->withHeaders([
  1361. 'Link' => $link,
  1362. ]);
  1363. }
  1364. return $res;
  1365. }
  1366. /**
  1367. * GET /api/v1/timelines/home
  1368. *
  1369. *
  1370. * @return StatusTransformer
  1371. */
  1372. public function timelineHome(Request $request)
  1373. {
  1374. $this->validate($request,[
  1375. 'page' => 'nullable|integer|max:40',
  1376. 'min_id' => 'nullable|integer|min:0|max:' . PHP_INT_MAX,
  1377. 'max_id' => 'nullable|integer|min:0|max:' . PHP_INT_MAX,
  1378. 'limit' => 'nullable|integer|max:80'
  1379. ]);
  1380. $page = $request->input('page');
  1381. $min = $request->input('min_id');
  1382. $max = $request->input('max_id');
  1383. $limit = $request->input('limit') ?? 3;
  1384. $pid = $request->user()->profile_id;
  1385. $following = Cache::remember('profile:following:'.$pid, now()->addMinutes(1440), function() use($pid) {
  1386. $following = Follower::whereProfileId($pid)->pluck('following_id');
  1387. return $following->push($pid)->toArray();
  1388. });
  1389. if($min || $max) {
  1390. $dir = $min ? '>' : '<';
  1391. $id = $min ?? $max;
  1392. $res = Status::select(
  1393. 'id',
  1394. 'profile_id',
  1395. 'type',
  1396. 'visibility',
  1397. 'created_at'
  1398. )
  1399. ->whereIn('type', ['photo', 'photo:album', 'video', 'video:album', 'photo:video:album'])
  1400. ->where('id', $dir, $id)
  1401. ->whereIn('profile_id', $following)
  1402. ->whereIn('visibility',['public', 'unlisted', 'private'])
  1403. ->latest()
  1404. ->take($limit)
  1405. ->get()
  1406. ->map(function($s) use($pid) {
  1407. $status = StatusService::getMastodon($s['id']);
  1408. if(!$status || !isset($status['account']) || !isset($status['account']['id'])) {
  1409. return false;
  1410. }
  1411. if($pid) {
  1412. $status['favourited'] = (bool) LikeService::liked($pid, $s['id']);
  1413. $status['reblogged'] = (bool) ReblogService::get($pid, $status['id']);
  1414. }
  1415. return $status;
  1416. })
  1417. ->filter(function($status) {
  1418. return $status && isset($status['account']);
  1419. })
  1420. ->values()
  1421. ->toArray();
  1422. } else {
  1423. $res = Status::select(
  1424. 'id',
  1425. 'profile_id',
  1426. 'type',
  1427. 'visibility',
  1428. 'created_at'
  1429. )
  1430. ->whereIn('type', ['photo', 'photo:album', 'video', 'video:album', 'photo:video:album'])
  1431. ->whereIn('profile_id', $following)
  1432. ->whereIn('visibility',['public', 'unlisted', 'private'])
  1433. ->latest()
  1434. ->take($limit)
  1435. ->get()
  1436. ->map(function($s) use($pid) {
  1437. $status = StatusService::getMastodon($s['id']);
  1438. if(!$status || !isset($status['account']) || !isset($status['account']['id'])) {
  1439. return false;
  1440. }
  1441. if($pid) {
  1442. $status['favourited'] = (bool) LikeService::liked($pid, $s['id']);
  1443. $status['reblogged'] = (bool) ReblogService::get($pid, $status['id']);
  1444. }
  1445. return $status;
  1446. })
  1447. ->filter(function($status) {
  1448. return $status && isset($status['account']);
  1449. })
  1450. ->values()
  1451. ->toArray();
  1452. }
  1453. return response()->json($res);
  1454. }
  1455. /**
  1456. * GET /api/v1/conversations
  1457. *
  1458. * Not implemented
  1459. *
  1460. * @return array
  1461. */
  1462. public function conversations(Request $request)
  1463. {
  1464. abort_if(!$request->user(), 403);
  1465. $this->validate($request, [
  1466. 'limit' => 'min:1|max:40',
  1467. 'scope' => 'nullable|in:inbox,sent,requests'
  1468. ]);
  1469. $limit = $request->input('limit', 20);
  1470. $scope = $request->input('scope', 'inbox');
  1471. $pid = $request->user()->profile_id;
  1472. if(config('database.default') == 'pgsql') {
  1473. $dms = DirectMessage::when($scope === 'inbox', function($q, $scope) use($pid) {
  1474. return $q->whereIsHidden(false)->whereToId($pid)->orWhere('from_id', $pid);
  1475. })
  1476. ->when($scope === 'sent', function($q, $scope) use($pid) {
  1477. return $q->whereFromId($pid);
  1478. })
  1479. ->when($scope === 'requests', function($q, $scope) use($pid) {
  1480. return $q->whereToId($pid)->whereIsHidden(true);
  1481. });
  1482. } else {
  1483. $dms = DirectMessage::when($scope === 'inbox', function($q, $scope) use($pid) {
  1484. return $q->whereIsHidden(false)->whereToId($pid)->orWhere('from_id', $pid)->groupBy('to_id');
  1485. })
  1486. ->when($scope === 'sent', function($q, $scope) use($pid) {
  1487. return $q->whereFromId($pid)->groupBy('to_id');
  1488. })
  1489. ->when($scope === 'requests', function($q, $scope) use($pid) {
  1490. return $q->whereToId($pid)->whereIsHidden(true);
  1491. });
  1492. }
  1493. $dms = $dms->latest()
  1494. ->simplePaginate($limit)
  1495. ->map(function($dm) use($pid) {
  1496. $from = $pid == $dm->to_id ? $dm->from_id : $dm->to_id;
  1497. $res = [
  1498. 'id' => $dm->id,
  1499. 'unread' => false,
  1500. 'accounts' => [
  1501. AccountService::getMastodon($from)
  1502. ],
  1503. 'last_status' => StatusService::getDirectMessage($dm->status_id)
  1504. ];
  1505. return $res;
  1506. })
  1507. ->filter(function($dm) {
  1508. return isset($dm['accounts']) && count($dm['accounts']);
  1509. })
  1510. ->unique(function($item, $key) {
  1511. return $item['accounts'][0]['id'];
  1512. })
  1513. ->values();
  1514. return response()->json($dms);
  1515. }
  1516. /**
  1517. * GET /api/v1/timelines/public
  1518. *
  1519. *
  1520. * @return StatusTransformer
  1521. */
  1522. public function timelinePublic(Request $request)
  1523. {
  1524. $this->validate($request,[
  1525. 'min_id' => 'nullable|integer|min:0|max:' . PHP_INT_MAX,
  1526. 'max_id' => 'nullable|integer|min:0|max:' . PHP_INT_MAX,
  1527. 'limit' => 'nullable|integer|max:80'
  1528. ]);
  1529. $min = $request->input('min_id');
  1530. $max = $request->input('max_id');
  1531. $limit = $request->input('limit') ?? 3;
  1532. $user = $request->user();
  1533. $filtered = $user ? UserFilterService::filters($user->profile_id) : [];
  1534. Cache::remember('api:v1:timelines:public:cache_check', 10368000, function() {
  1535. if(PublicTimelineService::count() == 0) {
  1536. PublicTimelineService::warmCache(true, 400);
  1537. }
  1538. });
  1539. if ($max) {
  1540. $feed = PublicTimelineService::getRankedMaxId($max, $limit);
  1541. } else if ($min) {
  1542. $feed = PublicTimelineService::getRankedMinId($min, $limit);
  1543. } else {
  1544. $feed = PublicTimelineService::get(0, $limit);
  1545. }
  1546. $res = collect($feed)
  1547. ->map(function($k) use($user) {
  1548. $status = StatusService::getMastodon($k);
  1549. if(!$status || !isset($status['account']) || !isset($status['account']['id'])) {
  1550. return false;
  1551. }
  1552. if($user) {
  1553. $status['favourited'] = (bool) LikeService::liked($user->profile_id, $k);
  1554. $status['reblogged'] = (bool) ReblogService::get($user->profile_id, $status['id']);
  1555. }
  1556. return $status;
  1557. })
  1558. ->filter(function($s) use($filtered) {
  1559. return $s && isset($s['account']) && in_array($s['account']['id'], $filtered) == false;
  1560. })
  1561. ->values()
  1562. ->toArray();
  1563. return response()->json($res);
  1564. }
  1565. /**
  1566. * GET /api/v1/statuses/{id}
  1567. *
  1568. * @param integer $id
  1569. *
  1570. * @return StatusTransformer
  1571. */
  1572. public function statusById(Request $request, $id)
  1573. {
  1574. abort_if(!$request->user(), 403);
  1575. $user = $request->user();
  1576. $res = StatusService::getMastodon($id, false);
  1577. if(!$res || !isset($res['visibility'])) {
  1578. abort(404);
  1579. }
  1580. $scope = $res['visibility'];
  1581. if(!in_array($scope, ['public', 'unlisted'])) {
  1582. if($scope === 'private') {
  1583. if($res['account']['id'] != $user->profile_id) {
  1584. abort_unless(FollowerService::follows($user->profile_id, $res['account']['id']), 403);
  1585. }
  1586. } else {
  1587. abort(400, 'Invalid request');
  1588. }
  1589. }
  1590. $res['favourited'] = LikeService::liked($user->profile_id, $res['id']);
  1591. $res['reblogged'] = ReblogService::get($user->profile_id, $res['id']);
  1592. return response()->json($res);
  1593. }
  1594. /**
  1595. * GET /api/v1/statuses/{id}/context
  1596. *
  1597. * @param integer $id
  1598. *
  1599. * @return StatusTransformer
  1600. */
  1601. public function statusContext(Request $request, $id)
  1602. {
  1603. abort_if(!$request->user(), 403);
  1604. $user = $request->user();
  1605. $status = Status::findOrFail($id);
  1606. if($status->profile_id !== $user->profile_id) {
  1607. if($status->scope == 'private') {
  1608. abort_if(!$status->profile->followedBy($user->profile), 403);
  1609. } else {
  1610. abort_if(!in_array($status->scope, ['public','unlisted']), 403);
  1611. }
  1612. }
  1613. if($status->comments_disabled) {
  1614. $res = [
  1615. 'ancestors' => [],
  1616. 'descendants' => []
  1617. ];
  1618. } else {
  1619. $ancestors = $status->parent();
  1620. if($ancestors) {
  1621. $ares = new Fractal\Resource\Item($ancestors, new StatusTransformer());
  1622. $ancestors = [
  1623. $this->fractal->createData($ares)->toArray()
  1624. ];
  1625. } else {
  1626. $ancestors = [];
  1627. }
  1628. $descendants = Status::whereInReplyToId($id)->latest()->limit(20)->get();
  1629. $dres = new Fractal\Resource\Collection($descendants, new StatusTransformer());
  1630. $descendants = $this->fractal->createData($dres)->toArray();
  1631. $res = [
  1632. 'ancestors' => $ancestors,
  1633. 'descendants' => $descendants
  1634. ];
  1635. }
  1636. return response()->json($res);
  1637. }
  1638. /**
  1639. * GET /api/v1/statuses/{id}/card
  1640. *
  1641. * @param integer $id
  1642. *
  1643. * @return StatusTransformer
  1644. */
  1645. public function statusCard(Request $request, $id)
  1646. {
  1647. abort_if(!$request->user(), 403);
  1648. $user = $request->user();
  1649. $status = Status::findOrFail($id);
  1650. if($status->profile_id !== $user->profile_id) {
  1651. if($status->scope == 'private') {
  1652. abort_if(!$status->profile->followedBy($user->profile), 403);
  1653. } else {
  1654. abort_if(!in_array($status->scope, ['public','unlisted']), 403);
  1655. }
  1656. }
  1657. // Return empty response since we don't handle support cards
  1658. $res = [];
  1659. return response()->json($res);
  1660. }
  1661. /**
  1662. * GET /api/v1/statuses/{id}/reblogged_by
  1663. *
  1664. * @param integer $id
  1665. *
  1666. * @return AccountTransformer
  1667. */
  1668. public function statusRebloggedBy(Request $request, $id)
  1669. {
  1670. abort_if(!$request->user(), 403);
  1671. $this->validate($request, [
  1672. 'page' => 'nullable|integer|min:1|max:40',
  1673. 'limit' => 'nullable|integer|min:1|max:80'
  1674. ]);
  1675. $limit = $request->input('limit') ?? 40;
  1676. $user = $request->user();
  1677. $status = Status::findOrFail($id);
  1678. if($status->profile_id !== $user->profile_id) {
  1679. if($status->scope == 'private') {
  1680. abort_if(!$status->profile->followedBy($user->profile), 403);
  1681. } else {
  1682. abort_if(!in_array($status->scope, ['public','unlisted']), 403);
  1683. }
  1684. }
  1685. $shared = $status->sharedBy()->latest()->simplePaginate($limit);
  1686. $resource = new Fractal\Resource\Collection($shared, new AccountTransformer());
  1687. $res = $this->fractal->createData($resource)->toArray();
  1688. $url = $request->url();
  1689. $page = $request->input('page', 1);
  1690. $next = $page < 40 ? $page + 1 : 40;
  1691. $prev = $page > 1 ? $page - 1 : 1;
  1692. $links = '<'.$url.'?page='.$next.'&limit='.$limit.'>; rel="next", <'.$url.'?page='.$prev.'&limit='.$limit.'>; rel="prev"';
  1693. return response()->json($res, 200, ['Link' => $links]);
  1694. }
  1695. /**
  1696. * GET /api/v1/statuses/{id}/favourited_by
  1697. *
  1698. * @param integer $id
  1699. *
  1700. * @return AccountTransformer
  1701. */
  1702. public function statusFavouritedBy(Request $request, $id)
  1703. {
  1704. abort_if(!$request->user(), 403);
  1705. $this->validate($request, [
  1706. 'page' => 'nullable|integer|min:1|max:40',
  1707. 'limit' => 'nullable|integer|min:1|max:80'
  1708. ]);
  1709. $page = $request->input('page', 1);
  1710. $limit = $request->input('limit') ?? 40;
  1711. $user = $request->user();
  1712. $status = Status::findOrFail($id);
  1713. $offset = $page == 1 ? 0 : ($page * $limit - $limit);
  1714. if($offset > 100) {
  1715. if($user->profile_id != $status->profile_id) {
  1716. return [];
  1717. }
  1718. }
  1719. if($status->profile_id !== $user->profile_id) {
  1720. if($status->scope == 'private') {
  1721. abort_if(!$status->profile->followedBy($user->profile), 403);
  1722. } else {
  1723. abort_if(!in_array($status->scope, ['public','unlisted']), 403);
  1724. }
  1725. }
  1726. $res = DB::table('likes')
  1727. ->select('likes.id', 'likes.profile_id', 'likes.status_id', 'followers.created_at')
  1728. ->leftJoin('followers', function($join) use($user, $status) {
  1729. return $join->on('likes.profile_id', '=', 'followers.following_id')
  1730. ->where('followers.profile_id', $user->profile_id)
  1731. ->where('likes.status_id', $status->id);
  1732. })
  1733. ->whereStatusId($status->id)
  1734. ->orderByDesc('followers.created_at')
  1735. ->offset($offset)
  1736. ->limit($limit)
  1737. ->get()
  1738. ->map(function($like) {
  1739. $account = AccountService::getMastodon($like->profile_id);
  1740. $account['follows'] = isset($like->created_at);
  1741. return $account;
  1742. })
  1743. ->filter(function($account) use($user) {
  1744. return $account && isset($account['id']) && $account['id'] != $user->profile_id;
  1745. })
  1746. ->values();
  1747. $url = $request->url();
  1748. $page = $request->input('page', 1);
  1749. $next = $page < 40 ? $page + 1 : 40;
  1750. $prev = $page > 1 ? $page - 1 : 1;
  1751. $links = '<'.$url.'?page='.$next.'&limit='.$limit.'>; rel="next", <'.$url.'?page='.$prev.'&limit='.$limit.'>; rel="prev"';
  1752. return response()->json($res, 200, ['Link' => $links]);
  1753. }
  1754. /**
  1755. * POST /api/v1/statuses
  1756. *
  1757. *
  1758. * @return StatusTransformer
  1759. */
  1760. public function statusCreate(Request $request)
  1761. {
  1762. abort_if(!$request->user(), 403);
  1763. $this->validate($request, [
  1764. 'status' => 'nullable|string',
  1765. 'in_reply_to_id' => 'nullable|integer',
  1766. 'media_ids' => 'array|max:' . config_cache('pixelfed.max_album_length'),
  1767. 'media_ids.*' => 'integer|min:1',
  1768. 'sensitive' => 'nullable|boolean',
  1769. 'visibility' => 'string|in:private,unlisted,public',
  1770. ]);
  1771. if(config('costar.enabled') == true) {
  1772. $blockedKeywords = config('costar.keyword.block');
  1773. if($blockedKeywords !== null && $request->status) {
  1774. $keywords = config('costar.keyword.block');
  1775. foreach($keywords as $kw) {
  1776. if(Str::contains($request->status, $kw) == true) {
  1777. abort(400, 'Invalid object. Contains banned keyword.');
  1778. }
  1779. }
  1780. }
  1781. }
  1782. if(!$request->filled('media_ids') && !$request->filled('in_reply_to_id')) {
  1783. abort(403, 'Empty statuses are not allowed');
  1784. }
  1785. $ids = $request->input('media_ids');
  1786. $in_reply_to_id = $request->input('in_reply_to_id');
  1787. $user = $request->user();
  1788. $profile = $user->profile;
  1789. $limitKey = 'compose:rate-limit:store:' . $user->id;
  1790. $limitTtl = now()->addMinutes(15);
  1791. $limitReached = Cache::remember($limitKey, $limitTtl, function() use($user) {
  1792. $dailyLimit = Status::whereProfileId($user->profile_id)
  1793. ->whereNull('in_reply_to_id')
  1794. ->whereNull('reblog_of_id')
  1795. ->where('created_at', '>', now()->subDays(1))
  1796. ->count();
  1797. return $dailyLimit >= 100;
  1798. });
  1799. abort_if($limitReached == true, 429);
  1800. $visibility = $profile->is_private ? 'private' : (
  1801. $profile->unlisted == true &&
  1802. $request->input('visibility', 'public') == 'public' ?
  1803. 'unlisted' :
  1804. $request->input('visibility', 'public'));
  1805. if($user->last_active_at == null) {
  1806. return [];
  1807. }
  1808. $content = strip_tags($request->input('status'));
  1809. $rendered = Autolink::create()->autolink($content);
  1810. if($in_reply_to_id) {
  1811. $parent = Status::findOrFail($in_reply_to_id);
  1812. $status = new Status;
  1813. $status->caption = $content;
  1814. $status->rendered = $rendered;
  1815. $status->scope = $visibility;
  1816. $status->visibility = $visibility;
  1817. $status->profile_id = $user->profile_id;
  1818. $status->is_nsfw = $user->profile->cw == true ? true : $request->input('sensitive', false);
  1819. $status->in_reply_to_id = $parent->id;
  1820. $status->in_reply_to_profile_id = $parent->profile_id;
  1821. $status->save();
  1822. StatusService::del($parent->id);
  1823. Cache::forget('status:replies:all:' . $parent->id);
  1824. }
  1825. if($ids) {
  1826. if(Media::whereUserId($user->id)
  1827. ->whereNull('status_id')
  1828. ->find($ids)
  1829. ->count() == 0
  1830. ) {
  1831. abort(400, 'Invalid media_ids');
  1832. }
  1833. if(!$in_reply_to_id) {
  1834. $status = new Status;
  1835. $status->caption = $content;
  1836. $status->rendered = $rendered;
  1837. $status->profile_id = $user->profile_id;
  1838. $status->scope = 'draft';
  1839. $status->is_nsfw = $user->profile->cw == true ? true : $request->input('sensitive', false);
  1840. $status->save();
  1841. }
  1842. $mimes = [];
  1843. foreach($ids as $k => $v) {
  1844. if($k + 1 > config_cache('pixelfed.max_album_length')) {
  1845. continue;
  1846. }
  1847. $m = Media::whereUserId($user->id)->whereNull('status_id')->findOrFail($v);
  1848. if($m->profile_id !== $user->profile_id || $m->status_id) {
  1849. abort(403, 'Invalid media id');
  1850. }
  1851. $m->status_id = $status->id;
  1852. $m->save();
  1853. array_push($mimes, $m->mime);
  1854. }
  1855. if(empty($mimes)) {
  1856. $status->delete();
  1857. abort(400, 'Invalid media ids');
  1858. }
  1859. $status->scope = $visibility;
  1860. $status->visibility = $visibility;
  1861. $status->type = StatusController::mimeTypeCheck($mimes);
  1862. $status->save();
  1863. }
  1864. if(!$status) {
  1865. abort(500, 'An error occured.');
  1866. }
  1867. NewStatusPipeline::dispatch($status);
  1868. if($status->in_reply_to_id) {
  1869. CommentPipeline::dispatch($parent, $status);
  1870. }
  1871. Cache::forget('user:account:id:'.$user->id);
  1872. Cache::forget('_api:statuses:recent_9:'.$user->profile_id);
  1873. Cache::forget('profile:status_count:'.$user->profile_id);
  1874. Cache::forget($user->storageUsedKey());
  1875. Cache::forget('profile:embed:' . $status->profile_id);
  1876. Cache::forget($limitKey);
  1877. $resource = new Fractal\Resource\Item($status, new StatusTransformer());
  1878. $res = $this->fractal->createData($resource)->toArray();
  1879. return response()->json($res);
  1880. }
  1881. /**
  1882. * DELETE /api/v1/statuses
  1883. *
  1884. * @param integer $id
  1885. *
  1886. * @return null
  1887. */
  1888. public function statusDelete(Request $request, $id)
  1889. {
  1890. abort_if(!$request->user(), 403);
  1891. $status = Status::whereProfileId($request->user()->profile->id)
  1892. ->findOrFail($id);
  1893. $resource = new Fractal\Resource\Item($status, new StatusTransformer());
  1894. Cache::forget('profile:status_count:'.$status->profile_id);
  1895. StatusDelete::dispatch($status);
  1896. $res = $this->fractal->createData($resource)->toArray();
  1897. $res['text'] = $res['content'];
  1898. unset($res['content']);
  1899. return response()->json($res);
  1900. }
  1901. /**
  1902. * POST /api/v1/statuses/{id}/reblog
  1903. *
  1904. * @param integer $id
  1905. *
  1906. * @return StatusTransformer
  1907. */
  1908. public function statusShare(Request $request, $id)
  1909. {
  1910. abort_if(!$request->user(), 403);
  1911. $user = $request->user();
  1912. $status = Status::whereScope('public')->findOrFail($id);
  1913. if($status->profile_id !== $user->profile_id) {
  1914. if($status->scope == 'private') {
  1915. abort_if(!$status->profile->followedBy($user->profile), 403);
  1916. } else {
  1917. abort_if(!in_array($status->scope, ['public','unlisted']), 403);
  1918. }
  1919. }
  1920. $share = Status::firstOrCreate([
  1921. 'profile_id' => $user->profile_id,
  1922. 'reblog_of_id' => $status->id,
  1923. 'in_reply_to_profile_id' => $status->profile_id,
  1924. 'scope' => 'public',
  1925. 'visibility' => 'public'
  1926. ]);
  1927. if($share->wasRecentlyCreated == true) {
  1928. SharePipeline::dispatch($share);
  1929. }
  1930. StatusService::del($status->id);
  1931. ReblogService::add($user->profile_id, $status->id);
  1932. $res = StatusService::getMastodon($status->id);
  1933. $res['reblogged'] = true;
  1934. return response()->json($res);
  1935. }
  1936. /**
  1937. * POST /api/v1/statuses/{id}/unreblog
  1938. *
  1939. * @param integer $id
  1940. *
  1941. * @return StatusTransformer
  1942. */
  1943. public function statusUnshare(Request $request, $id)
  1944. {
  1945. abort_if(!$request->user(), 403);
  1946. $user = $request->user();
  1947. $status = Status::whereScope('public')->findOrFail($id);
  1948. if($status->profile_id !== $user->profile_id) {
  1949. if($status->scope == 'private') {
  1950. abort_if(!$status->profile->followedBy($user->profile), 403);
  1951. } else {
  1952. abort_if(!in_array($status->scope, ['public','unlisted']), 403);
  1953. }
  1954. }
  1955. $reblog = Status::whereProfileId($user->profile_id)
  1956. ->whereReblogOfId($status->id)
  1957. ->first();
  1958. if(!$reblog) {
  1959. $resource = new Fractal\Resource\Item($status, new StatusTransformer());
  1960. $res = $this->fractal->createData($resource)->toArray();
  1961. return response()->json($res);
  1962. }
  1963. UndoSharePipeline::dispatch($reblog);
  1964. ReblogService::del($user->profile_id, $status->id);
  1965. $res = StatusService::getMastodon($status->id);
  1966. $res['reblogged'] = true;
  1967. return response()->json($res);
  1968. }
  1969. /**
  1970. * GET /api/v1/timelines/tag/{hashtag}
  1971. *
  1972. * @param string $hashtag
  1973. *
  1974. * @return StatusTransformer
  1975. */
  1976. public function timelineHashtag(Request $request, $hashtag)
  1977. {
  1978. $this->validate($request,[
  1979. 'page' => 'nullable|integer|max:40',
  1980. 'min_id' => 'nullable|integer|min:0|max:' . PHP_INT_MAX,
  1981. 'max_id' => 'nullable|integer|min:0|max:' . PHP_INT_MAX,
  1982. 'limit' => 'nullable|integer|max:40'
  1983. ]);
  1984. $tag = Hashtag::whereName($hashtag)
  1985. ->orWhere('slug', $hashtag)
  1986. ->first();
  1987. if(!$tag) {
  1988. return response()->json([]);
  1989. }
  1990. $min = $request->input('min_id');
  1991. $max = $request->input('max_id');
  1992. $limit = $request->input('limit', 20);
  1993. if(!$min && !$max) {
  1994. $id = 1;
  1995. $dir = '>';
  1996. } else {
  1997. $dir = $min ? '>' : '<';
  1998. $id = $min ?? $max;
  1999. }
  2000. $res = StatusHashtag::whereHashtagId($tag->id)
  2001. ->whereStatusVisibility('public')
  2002. ->whereHas('media')
  2003. ->where('status_id', $dir, $id)
  2004. ->latest()
  2005. ->limit($limit)
  2006. ->pluck('status_id')
  2007. ->filter(function($i) {
  2008. return StatusService::getMastodon($i);
  2009. })
  2010. ->map(function ($i) {
  2011. return StatusService::getMastodon($i);
  2012. })
  2013. ->filter()
  2014. ->values()
  2015. ->toArray();
  2016. return response()->json($res, 200, [], JSON_PRETTY_PRINT);
  2017. }
  2018. /**
  2019. * GET /api/v1/bookmarks
  2020. *
  2021. *
  2022. *
  2023. * @return StatusTransformer
  2024. */
  2025. public function bookmarks(Request $request)
  2026. {
  2027. abort_if(!$request->user(), 403);
  2028. $this->validate($request, [
  2029. 'limit' => 'nullable|integer|min:1|max:40',
  2030. 'max_id' => 'nullable|integer|min:0',
  2031. 'since_id' => 'nullable|integer|min:0',
  2032. 'min_id' => 'nullable|integer|min:0'
  2033. ]);
  2034. $pid = $request->user()->profile_id;
  2035. $limit = $request->input('limit') ?? 20;
  2036. $max_id = $request->input('max_id');
  2037. $since_id = $request->input('since_id');
  2038. $min_id = $request->input('min_id');
  2039. $dir = $min_id ? '>' : '<';
  2040. $id = $min_id ?? $max_id;
  2041. if($id) {
  2042. $bookmarks = Bookmark::whereProfileId($pid)
  2043. ->where('status_id', $dir, $id)
  2044. ->limit($limit)
  2045. ->pluck('status_id');
  2046. } else {
  2047. $bookmarks = Bookmark::whereProfileId($pid)
  2048. ->latest()
  2049. ->limit($limit)
  2050. ->pluck('status_id');
  2051. }
  2052. $res = [];
  2053. foreach($bookmarks as $id) {
  2054. $res[] = \App\Services\StatusService::getMastodon($id);
  2055. }
  2056. return $res;
  2057. }
  2058. /**
  2059. * POST /api/v1/statuses/{id}/bookmark
  2060. *
  2061. *
  2062. *
  2063. * @return StatusTransformer
  2064. */
  2065. public function bookmarkStatus(Request $request, $id)
  2066. {
  2067. abort_if(!$request->user(), 403);
  2068. $status = Status::whereNull('uri')
  2069. ->whereScope('public')
  2070. ->findOrFail($id);
  2071. Bookmark::firstOrCreate([
  2072. 'status_id' => $status->id,
  2073. 'profile_id' => $request->user()->profile_id
  2074. ]);
  2075. $resource = new Fractal\Resource\Item($status, new StatusTransformer());
  2076. $res = $this->fractal->createData($resource)->toArray();
  2077. return response()->json($res);
  2078. }
  2079. /**
  2080. * POST /api/v1/statuses/{id}/unbookmark
  2081. *
  2082. *
  2083. *
  2084. * @return StatusTransformer
  2085. */
  2086. public function unbookmarkStatus(Request $request, $id)
  2087. {
  2088. abort_if(!$request->user(), 403);
  2089. $status = Status::whereNull('uri')
  2090. ->whereScope('public')
  2091. ->findOrFail($id);
  2092. Bookmark::firstOrCreate([
  2093. 'status_id' => $status->id,
  2094. 'profile_id' => $request->user()->profile_id
  2095. ]);
  2096. $bookmark = Bookmark::whereStatusId($status->id)
  2097. ->whereProfileId($request->user()->profile_id)
  2098. ->firstOrFail();
  2099. $bookmark->delete();
  2100. $resource = new Fractal\Resource\Item($status, new StatusTransformer());
  2101. $res = $this->fractal->createData($resource)->toArray();
  2102. return response()->json($res);
  2103. }
  2104. /**
  2105. * GET /api/v2/search
  2106. *
  2107. *
  2108. * @return array
  2109. */
  2110. public function searchV2(Request $request)
  2111. {
  2112. abort_if(!$request->user(), 403);
  2113. $this->validate($request, [
  2114. 'q' => 'required|string|min:1|max:80',
  2115. 'account_id' => 'nullable|string',
  2116. 'max_id' => 'nullable|string',
  2117. 'min_id' => 'nullable|string',
  2118. 'type' => 'nullable|in:accounts,hashtags,statuses',
  2119. 'exclude_unreviewed' => 'nullable',
  2120. 'resolve' => 'nullable',
  2121. 'limit' => 'nullable|integer|max:40',
  2122. 'offset' => 'nullable|integer',
  2123. 'following' => 'nullable'
  2124. ]);
  2125. return SearchApiV2Service::query($request);
  2126. }
  2127. /**
  2128. * GET /api/v1/discover/posts
  2129. *
  2130. *
  2131. * @return array
  2132. */
  2133. public function discoverPosts(Request $request)
  2134. {
  2135. abort_if(!$request->user(), 403);
  2136. $this->validate($request, [
  2137. 'limit' => 'integer|min:1|max:40'
  2138. ]);
  2139. $limit = $request->input('limit', 40);
  2140. $pid = $request->user()->profile_id;
  2141. $filters = UserFilterService::filters($pid);
  2142. $forYou = DiscoverService::getForYou();
  2143. $posts = $forYou->take(50)->map(function($post) {
  2144. return StatusService::getMastodon($post);
  2145. })
  2146. ->filter(function($post) use($filters) {
  2147. return $post &&
  2148. isset($post['account']) &&
  2149. isset($post['account']['id']) &&
  2150. !in_array($post['account']['id'], $filters);
  2151. })
  2152. ->take(12)
  2153. ->values();
  2154. return response()->json(compact('posts'));
  2155. }
  2156. /**
  2157. * GET /api/v2/statuses/{id}/replies
  2158. *
  2159. *
  2160. * @return array
  2161. */
  2162. public function statusReplies(Request $request, $id)
  2163. {
  2164. abort_if(!$request->user(), 403);
  2165. $this->validate($request, [
  2166. 'limit' => 'int|min:1|max:10',
  2167. 'sort' => 'in:all,newest,popular'
  2168. ]);
  2169. $limit = $request->input('limit', 3);
  2170. $pid = $request->user()->profile_id;
  2171. $status = StatusService::getMastodon($id, false);
  2172. abort_if(!$status, 404);
  2173. if($status['visibility'] == 'private') {
  2174. if($pid != $status['account']['id']) {
  2175. abort_unless(FollowerService::follows($pid, $status['account']['id']), 404);
  2176. }
  2177. }
  2178. $sortBy = $request->input('sort', 'all');
  2179. if($sortBy == 'all' && $status['replies_count'] && $request->has('refresh_cache')) {
  2180. if(!Cache::has('status:replies:all-rc:' . $id)) {
  2181. Cache::forget('status:replies:all:' . $id);
  2182. Cache::put('status:replies:all-rc:' . $id, true, 300);
  2183. }
  2184. }
  2185. if($sortBy == 'all' && !$request->has('cursor')) {
  2186. $ids = Cache::remember('status:replies:all:' . $id, 86400, function() use($id) {
  2187. return DB::table('statuses')
  2188. ->where('in_reply_to_id', $id)
  2189. ->orderBy('id')
  2190. ->cursorPaginate(3);
  2191. });
  2192. } else {
  2193. $ids = DB::table('statuses')
  2194. ->where('in_reply_to_id', $id)
  2195. ->when($sortBy, function($q, $sortBy) {
  2196. if($sortBy === 'all') {
  2197. return $q->orderBy('id');
  2198. }
  2199. if($sortBy === 'newest') {
  2200. return $q->orderByDesc('created_at');
  2201. }
  2202. if($sortBy === 'popular') {
  2203. return $q->orderByDesc('likes_count');
  2204. }
  2205. })
  2206. ->cursorPaginate($limit);
  2207. }
  2208. $data = $ids->map(function($post) use($pid) {
  2209. $status = StatusService::get($post->id);
  2210. if(!$status || !isset($status['id'])) {
  2211. return false;
  2212. }
  2213. $status['favourited'] = LikeService::liked($pid, $post->id);
  2214. return $status;
  2215. })
  2216. ->filter(function($post) {
  2217. return $post && isset($post['id']) && isset($post['account']);
  2218. })
  2219. ->values();
  2220. $res = [
  2221. 'data' => $data,
  2222. 'next' => $ids->nextPageUrl()
  2223. ];
  2224. return $res;
  2225. }
  2226. /**
  2227. * GET /api/v2/statuses/{id}/state
  2228. *
  2229. *
  2230. * @return array
  2231. */
  2232. public function statusState(Request $request, $id)
  2233. {
  2234. abort_if(!$request->user(), 403);
  2235. $status = Status::findOrFail($id);
  2236. $pid = $request->user()->profile_id;
  2237. abort_if(!in_array($status->scope, ['public', 'unlisted', 'private']), 404);
  2238. return StatusService::getState($status->id, $pid);
  2239. }
  2240. /**
  2241. * GET /api/v1/discover/accounts/popular
  2242. *
  2243. *
  2244. * @return array
  2245. */
  2246. public function discoverAccountsPopular(Request $request)
  2247. {
  2248. abort_if(!$request->user(), 403);
  2249. $pid = $request->user()->profile_id;
  2250. $ids = DB::table('profiles')
  2251. ->where('is_private', false)
  2252. ->whereNull('status')
  2253. ->orderByDesc('profiles.followers_count')
  2254. ->limit(20)
  2255. ->get();
  2256. $ids = $ids->map(function($profile) {
  2257. return AccountService::getMastodon($profile->id);
  2258. })
  2259. ->filter(function($profile) use($pid) {
  2260. return $profile &&
  2261. isset($profile['id']) &&
  2262. !FollowerService::follows($pid, $profile['id']) &&
  2263. $profile['id'] != $pid;
  2264. })
  2265. ->take(6)
  2266. ->values();
  2267. return response()->json($ids, 200, [], JSON_PRETTY_PRINT|JSON_UNESCAPED_SLASHES);
  2268. }
  2269. }