ApiV1Controller.php 85 KB

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