ApiV1Controller.php 94 KB

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