ApiV1Controller.php 87 KB

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