ApiV1Controller.php 88 KB

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