ApiV1Controller.php 76 KB

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