1
0

ApiV1Controller.php 82 KB

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