ApiV1Controller.php 79 KB

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