1
0

ApiV1Controller.php 72 KB

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