ApiV1Controller.php 79 KB

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