ApiV1Controller.php 93 KB

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