ApiV1Controller.php 93 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526
  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. $status = $napi ? StatusService::get($s['id'], false) : StatusService::getMastodon($s['id'], false);
  1836. if(!$status || !isset($status['account']) || !isset($status['account']['id'])) {
  1837. return false;
  1838. }
  1839. } catch(\Exception $e) {
  1840. return false;
  1841. }
  1842. if($pid) {
  1843. $status['favourited'] = (bool) LikeService::liked($pid, $s['id']);
  1844. $status['reblogged'] = (bool) ReblogService::get($pid, $status['id']);
  1845. }
  1846. return $status;
  1847. })
  1848. ->filter(function($status) {
  1849. return $status && isset($status['account']);
  1850. })
  1851. ->take($limit)
  1852. ->values();
  1853. } else {
  1854. $res = Status::select(
  1855. 'id',
  1856. 'profile_id',
  1857. 'type',
  1858. 'visibility',
  1859. 'in_reply_to_id',
  1860. 'reblog_of_id',
  1861. )
  1862. ->whereNull(['in_reply_to_id', 'reblog_of_id'])
  1863. ->whereIntegerInRaw('profile_id', $following)
  1864. ->whereIn('type', ['photo', 'photo:album', 'video', 'video:album', 'photo:video:album'])
  1865. ->whereIn('visibility',['public', 'unlisted', 'private'])
  1866. ->orderByDesc('id')
  1867. ->take(($limit * 2))
  1868. ->get()
  1869. ->map(function($s) use($pid, $napi) {
  1870. try {
  1871. $account = AccountService::get($s['profile_id'], true);
  1872. if(!$account) {
  1873. return false;
  1874. }
  1875. $status = $napi ? StatusService::get($s['id'], false) : StatusService::getMastodon($s['id'], false);
  1876. if(!$status || !isset($status['account']) || !isset($status['account']['id'])) {
  1877. return false;
  1878. }
  1879. } catch(\Exception $e) {
  1880. return false;
  1881. }
  1882. if($pid) {
  1883. $status['favourited'] = (bool) LikeService::liked($pid, $s['id']);
  1884. $status['reblogged'] = (bool) ReblogService::get($pid, $status['id']);
  1885. }
  1886. return $status;
  1887. })
  1888. ->filter(function($status) {
  1889. return $status && isset($status['account']);
  1890. })
  1891. ->take($limit)
  1892. ->values();
  1893. }
  1894. $baseUrl = config('app.url') . '/api/v1/timelines/home?limit=' . $limit . '&';
  1895. $minId = $res->map(function($s) {
  1896. return ['id' => $s['id']];
  1897. })->min('id');
  1898. $maxId = $res->map(function($s) {
  1899. return ['id' => $s['id']];
  1900. })->max('id');
  1901. if($minId == $maxId) {
  1902. $minId = null;
  1903. }
  1904. if($maxId) {
  1905. $link = '<'.$baseUrl.'max_id='.$minId.'>; rel="next"';
  1906. }
  1907. if($minId) {
  1908. $link = '<'.$baseUrl.'min_id='.$maxId.'>; rel="prev"';
  1909. }
  1910. if($maxId && $minId) {
  1911. $link = '<'.$baseUrl.'max_id='.$minId.'>; rel="next",<'.$baseUrl.'min_id='.$maxId.'>; rel="prev"';
  1912. }
  1913. $headers = isset($link) ? ['Link' => $link] : [];
  1914. return $this->json($res->toArray(), 200, $headers);
  1915. }
  1916. /**
  1917. * GET /api/v1/timelines/public
  1918. *
  1919. *
  1920. * @return StatusTransformer
  1921. */
  1922. public function timelinePublic(Request $request)
  1923. {
  1924. $this->validate($request,[
  1925. 'min_id' => 'nullable|integer|min:0|max:' . PHP_INT_MAX,
  1926. 'max_id' => 'nullable|integer|min:0|max:' . PHP_INT_MAX,
  1927. 'limit' => 'nullable|integer|max:100',
  1928. 'remote' => 'sometimes',
  1929. 'local' => 'sometimes'
  1930. ]);
  1931. $napi = $request->has(self::PF_API_ENTITY_KEY);
  1932. $min = $request->input('min_id');
  1933. $max = $request->input('max_id');
  1934. $limit = $request->input('limit') ?? 20;
  1935. $user = $request->user();
  1936. $remote = ($request->has('remote') && $request->input('remote') == true) || ($request->filled('local') && $request->input('local') != true);
  1937. $filtered = $user ? UserFilterService::filters($user->profile_id) : [];
  1938. if((!$request->has('local') || $remote) && config('instance.timeline.network.cached')) {
  1939. Cache::remember('api:v1:timelines:network:cache_check', 10368000, function() {
  1940. if(NetworkTimelineService::count() == 0) {
  1941. NetworkTimelineService::warmCache(true, config('instance.timeline.network.cache_dropoff'));
  1942. }
  1943. });
  1944. if ($max) {
  1945. $feed = NetworkTimelineService::getRankedMaxId($max, $limit + 5);
  1946. } else if ($min) {
  1947. $feed = NetworkTimelineService::getRankedMinId($min, $limit + 5);
  1948. } else {
  1949. $feed = NetworkTimelineService::get(0, $limit + 5);
  1950. }
  1951. } else {
  1952. Cache::remember('api:v1:timelines:public:cache_check', 10368000, function() {
  1953. if(PublicTimelineService::count() == 0) {
  1954. PublicTimelineService::warmCache(true, 400);
  1955. }
  1956. });
  1957. if ($max) {
  1958. $feed = PublicTimelineService::getRankedMaxId($max, $limit + 5);
  1959. } else if ($min) {
  1960. $feed = PublicTimelineService::getRankedMinId($min, $limit + 5);
  1961. } else {
  1962. $feed = PublicTimelineService::get(0, $limit + 5);
  1963. }
  1964. }
  1965. $res = collect($feed)
  1966. ->filter(function($k) use($min, $max) {
  1967. if(!$min && !$max) {
  1968. return true;
  1969. }
  1970. if($min) {
  1971. return $min != $k;
  1972. }
  1973. if($max) {
  1974. return $max != $k;
  1975. }
  1976. })
  1977. ->map(function($k) use($user, $napi) {
  1978. $status = $napi ? StatusService::get($k) : StatusService::getMastodon($k);
  1979. if(!$status || !isset($status['account']) || !isset($status['account']['id'])) {
  1980. return false;
  1981. }
  1982. if($user) {
  1983. $status['favourited'] = (bool) LikeService::liked($user->profile_id, $k);
  1984. $status['reblogged'] = (bool) ReblogService::get($user->profile_id, $status['id']);
  1985. }
  1986. return $status;
  1987. })
  1988. ->filter(function($s) use($filtered) {
  1989. return $s && isset($s['account']) && in_array($s['account']['id'], $filtered) == false;
  1990. })
  1991. ->take($limit)
  1992. ->values();
  1993. $baseUrl = config('app.url') . '/api/v1/timelines/public?limit=' . $limit . '&';
  1994. if($remote) {
  1995. $baseUrl .= 'remote=1&';
  1996. }
  1997. $minId = $res->map(function($s) {
  1998. return ['id' => $s['id']];
  1999. })->min('id');
  2000. $maxId = $res->map(function($s) {
  2001. return ['id' => $s['id']];
  2002. })->max('id');
  2003. if($minId == $maxId) {
  2004. $minId = null;
  2005. }
  2006. if($maxId) {
  2007. $link = '<'.$baseUrl.'max_id='.$minId.'>; rel="next"';
  2008. }
  2009. if($minId) {
  2010. $link = '<'.$baseUrl.'min_id='.$maxId.'>; rel="prev"';
  2011. }
  2012. if($maxId && $minId) {
  2013. $link = '<'.$baseUrl.'max_id='.$minId.'>; rel="next",<'.$baseUrl.'min_id='.$maxId.'>; rel="prev"';
  2014. }
  2015. $headers = isset($link) ? ['Link' => $link] : [];
  2016. return $this->json($res->toArray(), 200, $headers);
  2017. }
  2018. /**
  2019. * GET /api/v1/conversations
  2020. *
  2021. * Not implemented
  2022. *
  2023. * @return array
  2024. */
  2025. public function conversations(Request $request)
  2026. {
  2027. abort_if(!$request->user(), 403);
  2028. $this->validate($request, [
  2029. 'limit' => 'min:1|max:40',
  2030. 'scope' => 'nullable|in:inbox,sent,requests'
  2031. ]);
  2032. $limit = $request->input('limit', 20);
  2033. $scope = $request->input('scope', 'inbox');
  2034. $pid = $request->user()->profile_id;
  2035. if(config('database.default') == 'pgsql') {
  2036. $dms = DirectMessage::when($scope === 'inbox', function($q, $scope) use($pid) {
  2037. return $q->whereIsHidden(false)->where('to_id', $pid)->orWhere('from_id', $pid);
  2038. })
  2039. ->when($scope === 'sent', function($q, $scope) use($pid) {
  2040. return $q->whereFromId($pid)->groupBy(['to_id', 'id']);
  2041. })
  2042. ->when($scope === 'requests', function($q, $scope) use($pid) {
  2043. return $q->whereToId($pid)->whereIsHidden(true);
  2044. });
  2045. } else {
  2046. $dms = Conversation::when($scope === 'inbox', function($q, $scope) use($pid) {
  2047. return $q->whereIsHidden(false)
  2048. ->where('to_id', $pid)
  2049. ->orWhere('from_id', $pid)
  2050. ->orderByDesc('status_id')
  2051. ->groupBy(['to_id', 'from_id']);
  2052. })
  2053. ->when($scope === 'sent', function($q, $scope) use($pid) {
  2054. return $q->whereFromId($pid)->groupBy('to_id');
  2055. })
  2056. ->when($scope === 'requests', function($q, $scope) use($pid) {
  2057. return $q->whereToId($pid)->whereIsHidden(true);
  2058. });
  2059. }
  2060. $dms = $dms->orderByDesc('status_id')
  2061. ->simplePaginate($limit)
  2062. ->map(function($dm) use($pid) {
  2063. $from = $pid == $dm->to_id ? $dm->from_id : $dm->to_id;
  2064. $res = [
  2065. 'id' => $dm->id,
  2066. 'unread' => false,
  2067. 'accounts' => [
  2068. AccountService::getMastodon($from)
  2069. ],
  2070. 'last_status' => StatusService::getDirectMessage($dm->status_id)
  2071. ];
  2072. return $res;
  2073. })
  2074. ->filter(function($dm) {
  2075. return isset($dm['accounts']) && count($dm['accounts']) && !empty($dm['last_status']);
  2076. })
  2077. ->unique(function($item, $key) {
  2078. return $item['accounts'][0]['id'];
  2079. })
  2080. ->values();
  2081. return $this->json($dms);
  2082. }
  2083. /**
  2084. * GET /api/v1/statuses/{id}
  2085. *
  2086. * @param integer $id
  2087. *
  2088. * @return StatusTransformer
  2089. */
  2090. public function statusById(Request $request, $id)
  2091. {
  2092. abort_if(!$request->user(), 403);
  2093. $user = $request->user();
  2094. $res = $request->has(self::PF_API_ENTITY_KEY) ? StatusService::get($id, false) : StatusService::getMastodon($id, false);
  2095. if(!$res || !isset($res['visibility'])) {
  2096. abort(404);
  2097. }
  2098. $scope = $res['visibility'];
  2099. if(!in_array($scope, ['public', 'unlisted'])) {
  2100. if($scope === 'private') {
  2101. if(intval($res['account']['id']) !== intval($user->profile_id)) {
  2102. abort_unless(FollowerService::follows($user->profile_id, $res['account']['id']), 403);
  2103. }
  2104. } else {
  2105. abort(400, 'Invalid request');
  2106. }
  2107. }
  2108. $res['favourited'] = LikeService::liked($user->profile_id, $res['id']);
  2109. $res['reblogged'] = ReblogService::get($user->profile_id, $res['id']);
  2110. $res['bookmarked'] = BookmarkService::get($user->profile_id, $res['id']);
  2111. return $this->json($res);
  2112. }
  2113. /**
  2114. * GET /api/v1/statuses/{id}/context
  2115. *
  2116. * @param integer $id
  2117. *
  2118. * @return StatusTransformer
  2119. */
  2120. public function statusContext(Request $request, $id)
  2121. {
  2122. abort_if(!$request->user(), 403);
  2123. $user = $request->user();
  2124. $pid = $user->profile_id;
  2125. $status = StatusService::getMastodon($id, false);
  2126. if(!$status || !isset($status['account'])) {
  2127. return response('', 404);
  2128. }
  2129. if(intval($status['account']['id']) !== intval($user->profile_id)) {
  2130. if($status['visibility'] == 'private') {
  2131. if(!FollowerService::follows($user->profile_id, $status['account']['id'])) {
  2132. return response('', 404);
  2133. }
  2134. } else {
  2135. if(!in_array($status['visibility'], ['public','unlisted'])) {
  2136. return response('', 404);
  2137. }
  2138. }
  2139. }
  2140. $ancestors = [];
  2141. $descendants = [];
  2142. if($status['in_reply_to_id']) {
  2143. $ancestors[] = StatusService::getMastodon($status['in_reply_to_id'], false);
  2144. }
  2145. if($status['replies_count']) {
  2146. $descendants = DB::table('statuses')
  2147. ->where('in_reply_to_id', $id)
  2148. ->limit(20)
  2149. ->pluck('id')
  2150. ->map(function($sid) {
  2151. return StatusService::getMastodon($sid, false);
  2152. })
  2153. ->filter(function($post) {
  2154. return $post && isset($post['account']);
  2155. })
  2156. ->map(function($status) use($pid) {
  2157. $status['favourited'] = LikeService::liked($pid, $status['id']);
  2158. $status['reblogged'] = ReblogService::get($pid, $status['id']);
  2159. return $status;
  2160. })
  2161. ->values();
  2162. }
  2163. $res = [
  2164. 'ancestors' => $ancestors,
  2165. 'descendants' => $descendants
  2166. ];
  2167. return $this->json($res);
  2168. }
  2169. /**
  2170. * GET /api/v1/statuses/{id}/card
  2171. *
  2172. * @param integer $id
  2173. *
  2174. * @return StatusTransformer
  2175. */
  2176. public function statusCard(Request $request, $id)
  2177. {
  2178. abort_if(!$request->user(), 403);
  2179. $res = [];
  2180. return response()->json($res);
  2181. }
  2182. /**
  2183. * GET /api/v1/statuses/{id}/reblogged_by
  2184. *
  2185. * @param integer $id
  2186. *
  2187. * @return AccountTransformer
  2188. */
  2189. public function statusRebloggedBy(Request $request, $id)
  2190. {
  2191. abort_if(!$request->user(), 403);
  2192. $this->validate($request, [
  2193. 'limit' => 'sometimes|integer|min:1|max:80'
  2194. ]);
  2195. $limit = $request->input('limit', 10);
  2196. $user = $request->user();
  2197. $pid = $user->profile_id;
  2198. $status = Status::findOrFail($id);
  2199. $account = AccountService::get($status->profile_id, true);
  2200. abort_if(!$account, 404);
  2201. $author = intval($status->profile_id) === intval($pid) || $user->is_admin;
  2202. $napi = $request->has(self::PF_API_ENTITY_KEY);
  2203. abort_if(
  2204. !$status->type ||
  2205. !in_array($status->type, ['photo','photo:album', 'photo:video:album', 'reply', 'text', 'video', 'video:album']),
  2206. 404,
  2207. );
  2208. if(!$author) {
  2209. if($status->scope == 'private') {
  2210. abort_if(!FollowerService::follows($pid, $status->profile_id), 403);
  2211. } else {
  2212. abort_if(!in_array($status->scope, ['public','unlisted']), 403);
  2213. }
  2214. if($request->has('cursor')) {
  2215. return $this->json([]);
  2216. }
  2217. }
  2218. $res = Status::where('reblog_of_id', $status->id)
  2219. ->orderByDesc('id')
  2220. ->cursorPaginate($limit)
  2221. ->withQueryString();
  2222. if(!$res) {
  2223. return $this->json([]);
  2224. }
  2225. $headers = [];
  2226. if($author && $res->hasPages()) {
  2227. $links = '';
  2228. if($res->onFirstPage()) {
  2229. if($res->nextPageUrl()) {
  2230. $links = '<' . $res->nextPageUrl() .'>; rel="prev"';
  2231. }
  2232. } else {
  2233. if($res->previousPageUrl()) {
  2234. $links = '<' . $res->previousPageUrl() .'>; rel="next"';
  2235. }
  2236. if($res->nextPageUrl()) {
  2237. if(!empty($links)) {
  2238. $links .= ', ';
  2239. }
  2240. $links .= '<' . $res->nextPageUrl() .'>; rel="prev"';
  2241. }
  2242. }
  2243. $headers = ['Link' => $links];
  2244. }
  2245. $res = $res->map(function($status) use($pid, $napi) {
  2246. $account = $napi ? AccountService::get($status->profile_id, true) : AccountService::getMastodon($status->profile_id, true);
  2247. if(!$account) {
  2248. return false;
  2249. }
  2250. if($napi) {
  2251. $account['follows'] = $status->profile_id == $pid ? null : FollowerService::follows($pid, $status->profile_id);
  2252. }
  2253. return $account;
  2254. })
  2255. ->filter(function($account) {
  2256. return $account && isset($account['id']);
  2257. })
  2258. ->values();
  2259. return $this->json($res, 200, $headers);
  2260. }
  2261. /**
  2262. * GET /api/v1/statuses/{id}/favourited_by
  2263. *
  2264. * @param integer $id
  2265. *
  2266. * @return AccountTransformer
  2267. */
  2268. public function statusFavouritedBy(Request $request, $id)
  2269. {
  2270. abort_if(!$request->user(), 403);
  2271. $this->validate($request, [
  2272. 'limit' => 'nullable|integer|min:1|max:80'
  2273. ]);
  2274. $limit = $request->input('limit', 10);
  2275. $user = $request->user();
  2276. $pid = $user->profile_id;
  2277. $status = Status::findOrFail($id);
  2278. $account = AccountService::get($status->profile_id, true);
  2279. abort_if(!$account, 404);
  2280. $author = intval($status->profile_id) === intval($pid) || $user->is_admin;
  2281. $napi = $request->has(self::PF_API_ENTITY_KEY);
  2282. abort_if(
  2283. !$status->type ||
  2284. !in_array($status->type, ['photo','photo:album', 'photo:video:album', 'reply', 'text', 'video', 'video:album']),
  2285. 404,
  2286. );
  2287. if(!$author) {
  2288. if($status->scope == 'private') {
  2289. abort_if(!FollowerService::follows($pid, $status->profile_id), 403);
  2290. } else {
  2291. abort_if(!in_array($status->scope, ['public','unlisted']), 403);
  2292. }
  2293. if($request->has('cursor')) {
  2294. return $this->json([]);
  2295. }
  2296. }
  2297. $res = Like::where('status_id', $status->id)
  2298. ->orderByDesc('id')
  2299. ->cursorPaginate($limit)
  2300. ->withQueryString();
  2301. if(!$res) {
  2302. return $this->json([]);
  2303. }
  2304. $headers = [];
  2305. if($author && $res->hasPages()) {
  2306. $links = '';
  2307. if($res->onFirstPage()) {
  2308. if($res->nextPageUrl()) {
  2309. $links = '<' . $res->nextPageUrl() .'>; rel="prev"';
  2310. }
  2311. } else {
  2312. if($res->previousPageUrl()) {
  2313. $links = '<' . $res->previousPageUrl() .'>; rel="next"';
  2314. }
  2315. if($res->nextPageUrl()) {
  2316. if(!empty($links)) {
  2317. $links .= ', ';
  2318. }
  2319. $links .= '<' . $res->nextPageUrl() .'>; rel="prev"';
  2320. }
  2321. }
  2322. $headers = ['Link' => $links];
  2323. }
  2324. $res = $res->map(function($like) use($pid, $napi) {
  2325. $account = $napi ? AccountService::get($like->profile_id, true) : AccountService::getMastodon($like->profile_id, true);
  2326. if(!$account) {
  2327. return false;
  2328. }
  2329. if($napi) {
  2330. $account['follows'] = $like->profile_id == $pid ? null : FollowerService::follows($pid, $like->profile_id);
  2331. }
  2332. return $account;
  2333. })
  2334. ->filter(function($account) {
  2335. return $account && isset($account['id']);
  2336. })
  2337. ->values();
  2338. return $this->json($res, 200, $headers);
  2339. }
  2340. /**
  2341. * POST /api/v1/statuses
  2342. *
  2343. *
  2344. * @return StatusTransformer
  2345. */
  2346. public function statusCreate(Request $request)
  2347. {
  2348. abort_if(!$request->user(), 403);
  2349. $this->validate($request, [
  2350. 'status' => 'nullable|string',
  2351. 'in_reply_to_id' => 'nullable',
  2352. 'media_ids' => 'sometimes|array|max:' . config_cache('pixelfed.max_album_length'),
  2353. 'sensitive' => 'nullable',
  2354. 'visibility' => 'string|in:private,unlisted,public',
  2355. 'spoiler_text' => 'sometimes|max:140',
  2356. 'place_id' => 'sometimes|integer|min:1|max:128769',
  2357. 'collection_ids' => 'sometimes|array|max:3',
  2358. 'comments_disabled' => 'sometimes|boolean',
  2359. ]);
  2360. if(config('costar.enabled') == true) {
  2361. $blockedKeywords = config('costar.keyword.block');
  2362. if($blockedKeywords !== null && $request->status) {
  2363. $keywords = config('costar.keyword.block');
  2364. foreach($keywords as $kw) {
  2365. if(Str::contains($request->status, $kw) == true) {
  2366. abort(400, 'Invalid object. Contains banned keyword.');
  2367. }
  2368. }
  2369. }
  2370. }
  2371. if(!$request->filled('media_ids') && !$request->filled('in_reply_to_id')) {
  2372. abort(403, 'Empty statuses are not allowed');
  2373. }
  2374. $ids = $request->input('media_ids');
  2375. $in_reply_to_id = $request->input('in_reply_to_id');
  2376. $user = $request->user();
  2377. $profile = $user->profile;
  2378. $limitKey = 'compose:rate-limit:store:' . $user->id;
  2379. $limitTtl = now()->addMinutes(15);
  2380. $limitReached = Cache::remember($limitKey, $limitTtl, function() use($user) {
  2381. $dailyLimit = Status::whereProfileId($user->profile_id)
  2382. ->whereNull('in_reply_to_id')
  2383. ->whereNull('reblog_of_id')
  2384. ->where('created_at', '>', now()->subDays(1))
  2385. ->count();
  2386. return $dailyLimit >= 100;
  2387. });
  2388. abort_if($limitReached == true, 429);
  2389. $visibility = $profile->is_private ? 'private' : (
  2390. $profile->unlisted == true &&
  2391. $request->input('visibility', 'public') == 'public' ?
  2392. 'unlisted' :
  2393. $request->input('visibility', 'public'));
  2394. if($user->last_active_at == null) {
  2395. return [];
  2396. }
  2397. $content = strip_tags($request->input('status'));
  2398. $rendered = Autolink::create()->autolink($content);
  2399. $cw = $user->profile->cw == true ? true : $request->input('sensitive', false);
  2400. $spoilerText = $cw && $request->filled('spoiler_text') ? $request->input('spoiler_text') : null;
  2401. if($in_reply_to_id) {
  2402. $parent = Status::findOrFail($in_reply_to_id);
  2403. if($parent->comments_disabled) {
  2404. return $this->json("Comments have been disabled on this post", 422);
  2405. }
  2406. $blocks = UserFilterService::blocks($parent->profile_id);
  2407. abort_if(in_array($profile->id, $blocks), 422, 'Cannot reply to this post at this time.');
  2408. $status = new Status;
  2409. $status->caption = $content;
  2410. $status->rendered = $rendered;
  2411. $status->scope = $visibility;
  2412. $status->visibility = $visibility;
  2413. $status->profile_id = $user->profile_id;
  2414. $status->is_nsfw = $cw;
  2415. $status->cw_summary = $spoilerText;
  2416. $status->in_reply_to_id = $parent->id;
  2417. $status->in_reply_to_profile_id = $parent->profile_id;
  2418. $status->save();
  2419. StatusService::del($parent->id);
  2420. Cache::forget('status:replies:all:' . $parent->id);
  2421. }
  2422. if($ids) {
  2423. if(Media::whereUserId($user->id)
  2424. ->whereNull('status_id')
  2425. ->find($ids)
  2426. ->count() == 0
  2427. ) {
  2428. abort(400, 'Invalid media_ids');
  2429. }
  2430. if(!$in_reply_to_id) {
  2431. $status = new Status;
  2432. $status->caption = $content;
  2433. $status->rendered = $rendered;
  2434. $status->profile_id = $user->profile_id;
  2435. $status->scope = 'draft';
  2436. $status->is_nsfw = $cw;
  2437. $status->cw_summary = $spoilerText;
  2438. if($request->has('place_id')) {
  2439. $status->place_id = $request->input('place_id');
  2440. }
  2441. $status->save();
  2442. }
  2443. $mimes = [];
  2444. foreach($ids as $k => $v) {
  2445. if($k + 1 > config_cache('pixelfed.max_album_length')) {
  2446. continue;
  2447. }
  2448. $m = Media::whereUserId($user->id)->whereNull('status_id')->findOrFail($v);
  2449. if($m->profile_id !== $user->profile_id || $m->status_id) {
  2450. abort(403, 'Invalid media id');
  2451. }
  2452. $m->order = $k + 1;
  2453. $m->status_id = $status->id;
  2454. $m->save();
  2455. array_push($mimes, $m->mime);
  2456. }
  2457. if(empty($mimes)) {
  2458. $status->delete();
  2459. abort(400, 'Invalid media ids');
  2460. }
  2461. if($request->has('comments_disabled') && $request->input('comments_disabled')) {
  2462. $status->comments_disabled = true;
  2463. }
  2464. $status->scope = $visibility;
  2465. $status->visibility = $visibility;
  2466. $status->type = StatusController::mimeTypeCheck($mimes);
  2467. $status->save();
  2468. }
  2469. if(!$status) {
  2470. abort(500, 'An error occured.');
  2471. }
  2472. NewStatusPipeline::dispatch($status);
  2473. if($status->in_reply_to_id) {
  2474. CommentPipeline::dispatch($parent, $status);
  2475. }
  2476. Cache::forget('user:account:id:'.$user->id);
  2477. Cache::forget('_api:statuses:recent_9:'.$user->profile_id);
  2478. Cache::forget('profile:status_count:'.$user->profile_id);
  2479. Cache::forget($user->storageUsedKey());
  2480. Cache::forget('profile:embed:' . $status->profile_id);
  2481. Cache::forget($limitKey);
  2482. if($request->has('collection_ids') && $ids) {
  2483. $collections = Collection::whereProfileId($user->profile_id)
  2484. ->find($request->input('collection_ids'))
  2485. ->each(function($collection) use($status) {
  2486. $count = $collection->items()->count();
  2487. $item = CollectionItem::firstOrCreate([
  2488. 'collection_id' => $collection->id,
  2489. 'object_type' => 'App\Status',
  2490. 'object_id' => $status->id
  2491. ],[
  2492. 'order' => $count,
  2493. ]);
  2494. CollectionService::addItem(
  2495. $collection->id,
  2496. $status->id,
  2497. $count
  2498. );
  2499. $collection->updated_at = now();
  2500. $collection->save();
  2501. CollectionService::setCollection($collection->id, $collection);
  2502. });
  2503. }
  2504. $res = StatusService::getMastodon($status->id, false);
  2505. $res['favourited'] = false;
  2506. $res['language'] = 'en';
  2507. $res['bookmarked'] = false;
  2508. $res['card'] = null;
  2509. return $this->json($res);
  2510. }
  2511. /**
  2512. * DELETE /api/v1/statuses
  2513. *
  2514. * @param integer $id
  2515. *
  2516. * @return null
  2517. */
  2518. public function statusDelete(Request $request, $id)
  2519. {
  2520. abort_if(!$request->user(), 403);
  2521. $status = Status::whereProfileId($request->user()->profile->id)
  2522. ->findOrFail($id);
  2523. $resource = new Fractal\Resource\Item($status, new StatusTransformer());
  2524. Cache::forget('profile:status_count:'.$status->profile_id);
  2525. StatusDelete::dispatch($status);
  2526. $res = $this->fractal->createData($resource)->toArray();
  2527. $res['text'] = $res['content'];
  2528. unset($res['content']);
  2529. return $this->json($res);
  2530. }
  2531. /**
  2532. * POST /api/v1/statuses/{id}/reblog
  2533. *
  2534. * @param integer $id
  2535. *
  2536. * @return StatusTransformer
  2537. */
  2538. public function statusShare(Request $request, $id)
  2539. {
  2540. abort_if(!$request->user(), 403);
  2541. $user = $request->user();
  2542. $status = Status::whereScope('public')->findOrFail($id);
  2543. if(intval($status->profile_id) !== intval($user->profile_id)) {
  2544. if($status->scope == 'private') {
  2545. abort_if(!FollowerService::follows($user->profile_id, $status->profile_id), 403);
  2546. } else {
  2547. abort_if(!in_array($status->scope, ['public','unlisted']), 403);
  2548. }
  2549. $blocks = UserFilterService::blocks($status->profile_id);
  2550. if($blocks && in_array($user->profile_id, $blocks)) {
  2551. abort(422);
  2552. }
  2553. }
  2554. $share = Status::firstOrCreate([
  2555. 'profile_id' => $user->profile_id,
  2556. 'reblog_of_id' => $status->id,
  2557. 'type' => 'share',
  2558. 'in_reply_to_profile_id' => $status->profile_id,
  2559. 'scope' => 'public',
  2560. 'visibility' => 'public'
  2561. ]);
  2562. SharePipeline::dispatch($share)->onQueue('low');
  2563. StatusService::del($status->id);
  2564. ReblogService::add($user->profile_id, $status->id);
  2565. $res = StatusService::getMastodon($status->id);
  2566. $res['reblogged'] = true;
  2567. return $this->json($res);
  2568. }
  2569. /**
  2570. * POST /api/v1/statuses/{id}/unreblog
  2571. *
  2572. * @param integer $id
  2573. *
  2574. * @return StatusTransformer
  2575. */
  2576. public function statusUnshare(Request $request, $id)
  2577. {
  2578. abort_if(!$request->user(), 403);
  2579. $user = $request->user();
  2580. $status = Status::whereScope('public')->findOrFail($id);
  2581. if(intval($status->profile_id) !== intval($user->profile_id)) {
  2582. if($status->scope == 'private') {
  2583. abort_if(!FollowerService::follows($user->profile_id, $status->profile_id), 403);
  2584. } else {
  2585. abort_if(!in_array($status->scope, ['public','unlisted']), 403);
  2586. }
  2587. }
  2588. $reblog = Status::whereProfileId($user->profile_id)
  2589. ->whereReblogOfId($status->id)
  2590. ->first();
  2591. if(!$reblog) {
  2592. $res = StatusService::getMastodon($status->id);
  2593. $res['reblogged'] = false;
  2594. return $this->json($res);
  2595. }
  2596. UndoSharePipeline::dispatch($reblog)->onQueue('low');
  2597. ReblogService::del($user->profile_id, $status->id);
  2598. $res = StatusService::getMastodon($status->id);
  2599. $res['reblogged'] = false;
  2600. return $this->json($res);
  2601. }
  2602. /**
  2603. * GET /api/v1/timelines/tag/{hashtag}
  2604. *
  2605. * @param string $hashtag
  2606. *
  2607. * @return StatusTransformer
  2608. */
  2609. public function timelineHashtag(Request $request, $hashtag)
  2610. {
  2611. abort_if(!$request->user(), 403);
  2612. $this->validate($request,[
  2613. 'page' => 'nullable|integer|max:40',
  2614. 'min_id' => 'nullable|integer|min:0|max:' . PHP_INT_MAX,
  2615. 'max_id' => 'nullable|integer|min:0|max:' . PHP_INT_MAX,
  2616. 'limit' => 'nullable|integer|max:100'
  2617. ]);
  2618. $tag = Hashtag::whereName($hashtag)
  2619. ->orWhere('slug', $hashtag)
  2620. ->first();
  2621. if(!$tag) {
  2622. return response()->json([]);
  2623. }
  2624. if($tag->is_banned == true) {
  2625. return $this->json([]);
  2626. }
  2627. $min = $request->input('min_id');
  2628. $max = $request->input('max_id');
  2629. $limit = $request->input('limit', 20);
  2630. if(!$min && !$max) {
  2631. $id = 1;
  2632. $dir = '>';
  2633. } else {
  2634. $dir = $min ? '>' : '<';
  2635. $id = $min ?? $max;
  2636. }
  2637. $res = StatusHashtag::whereHashtagId($tag->id)
  2638. ->whereStatusVisibility('public')
  2639. ->where('status_id', $dir, $id)
  2640. ->latest()
  2641. ->limit($limit)
  2642. ->pluck('status_id')
  2643. ->map(function ($i) {
  2644. if($i) {
  2645. return StatusService::getMastodon($i);
  2646. }
  2647. })
  2648. ->filter(function($i) {
  2649. return $i && isset($i['account']);
  2650. })
  2651. ->values()
  2652. ->toArray();
  2653. return $this->json($res);
  2654. }
  2655. /**
  2656. * GET /api/v1/bookmarks
  2657. *
  2658. *
  2659. *
  2660. * @return StatusTransformer
  2661. */
  2662. public function bookmarks(Request $request)
  2663. {
  2664. abort_if(!$request->user(), 403);
  2665. $this->validate($request, [
  2666. 'limit' => 'nullable|integer|min:1|max:40',
  2667. 'max_id' => 'nullable|integer|min:0',
  2668. 'since_id' => 'nullable|integer|min:0',
  2669. 'min_id' => 'nullable|integer|min:0'
  2670. ]);
  2671. $pe = $request->has('_pe');
  2672. $pid = $request->user()->profile_id;
  2673. $limit = $request->input('limit') ?? 20;
  2674. $max_id = $request->input('max_id');
  2675. $since_id = $request->input('since_id');
  2676. $min_id = $request->input('min_id');
  2677. $dir = $min_id ? '>' : '<';
  2678. $id = $min_id ?? $max_id;
  2679. $bookmarkQuery = Bookmark::whereProfileId($pid)
  2680. ->orderByDesc('id')
  2681. ->cursorPaginate($limit);
  2682. $bookmarks = $bookmarkQuery->map(function($bookmark) use($pid, $pe) {
  2683. $status = $pe ? StatusService::get($bookmark->status_id, false) : StatusService::getMastodon($bookmark->status_id, false);
  2684. if($status) {
  2685. $status['bookmarked'] = true;
  2686. $status['favourited'] = LikeService::liked($pid, $status['id']);
  2687. $status['reblogged'] = ReblogService::get($pid, $status['id']);
  2688. }
  2689. return $status;
  2690. })
  2691. ->filter()
  2692. ->values()
  2693. ->toArray();
  2694. $links = null;
  2695. $headers = [];
  2696. if($bookmarkQuery->nextCursor()) {
  2697. $links .= '<'.$bookmarkQuery->nextPageUrl().'&limit='.$limit.'>; rel="next"';
  2698. }
  2699. if($bookmarkQuery->previousCursor()) {
  2700. if($links != null) {
  2701. $links .= ', ';
  2702. }
  2703. $links .= '<'.$bookmarkQuery->previousPageUrl().'&limit='.$limit.'>; rel="prev"';
  2704. }
  2705. if($links) {
  2706. $headers = ['Link' => $links];
  2707. }
  2708. return $this->json($bookmarks, 200, $headers);
  2709. }
  2710. /**
  2711. * POST /api/v1/statuses/{id}/bookmark
  2712. *
  2713. *
  2714. *
  2715. * @return StatusTransformer
  2716. */
  2717. public function bookmarkStatus(Request $request, $id)
  2718. {
  2719. abort_if(!$request->user(), 403);
  2720. $status = Status::findOrFail($id);
  2721. $pid = $request->user()->profile_id;
  2722. abort_if($status->in_reply_to_id || $status->reblog_of_id, 404);
  2723. abort_if(!in_array($status->scope, ['public', 'unlisted', 'private']), 404);
  2724. abort_if(!in_array($status->type, ['photo','photo:album', 'video', 'video:album', 'photo:video:album']), 404);
  2725. if($status->scope == 'private') {
  2726. abort_if(
  2727. $pid !== $status->profile_id && !FollowerService::follows($pid, $status->profile_id),
  2728. 404,
  2729. 'Error: You cannot bookmark private posts from accounts you do not follow.'
  2730. );
  2731. }
  2732. Bookmark::firstOrCreate([
  2733. 'status_id' => $status->id,
  2734. 'profile_id' => $pid
  2735. ]);
  2736. BookmarkService::add($pid, $status->id);
  2737. $res = StatusService::getMastodon($status->id, false);
  2738. $res['bookmarked'] = true;
  2739. return $this->json($res);
  2740. }
  2741. /**
  2742. * POST /api/v1/statuses/{id}/unbookmark
  2743. *
  2744. *
  2745. *
  2746. * @return StatusTransformer
  2747. */
  2748. public function unbookmarkStatus(Request $request, $id)
  2749. {
  2750. abort_if(!$request->user(), 403);
  2751. $status = Status::findOrFail($id);
  2752. $pid = $request->user()->profile_id;
  2753. abort_if($status->in_reply_to_id || $status->reblog_of_id, 404);
  2754. abort_if(!in_array($status->scope, ['public', 'unlisted', 'private']), 404);
  2755. abort_if(!in_array($status->type, ['photo','photo:album', 'video', 'video:album', 'photo:video:album']), 404);
  2756. $bookmark = Bookmark::whereStatusId($status->id)
  2757. ->whereProfileId($pid)
  2758. ->first();
  2759. if($bookmark) {
  2760. BookmarkService::del($pid, $status->id);
  2761. $bookmark->delete();
  2762. }
  2763. $res = StatusService::getMastodon($status->id, false);
  2764. $res['bookmarked'] = false;
  2765. return $this->json($res);
  2766. }
  2767. /**
  2768. * GET /api/v2/search
  2769. *
  2770. *
  2771. * @return array
  2772. */
  2773. public function searchV2(Request $request)
  2774. {
  2775. abort_if(!$request->user(), 403);
  2776. $this->validate($request, [
  2777. 'q' => 'required|string|min:1|max:100',
  2778. 'account_id' => 'nullable|string',
  2779. 'max_id' => 'nullable|string',
  2780. 'min_id' => 'nullable|string',
  2781. 'type' => 'nullable|in:accounts,hashtags,statuses',
  2782. 'exclude_unreviewed' => 'nullable',
  2783. 'resolve' => 'nullable',
  2784. 'limit' => 'nullable|integer|max:40',
  2785. 'offset' => 'nullable|integer',
  2786. 'following' => 'nullable'
  2787. ]);
  2788. $mastodonMode = !$request->has('_pe');
  2789. return $this->json(SearchApiV2Service::query($request, $mastodonMode));
  2790. }
  2791. /**
  2792. * GET /api/v1/discover/posts
  2793. *
  2794. *
  2795. * @return array
  2796. */
  2797. public function discoverPosts(Request $request)
  2798. {
  2799. abort_if(!$request->user(), 403);
  2800. $this->validate($request, [
  2801. 'limit' => 'integer|min:1|max:40'
  2802. ]);
  2803. $limit = $request->input('limit', 40);
  2804. $pid = $request->user()->profile_id;
  2805. $filters = UserFilterService::filters($pid);
  2806. $forYou = DiscoverService::getForYou();
  2807. $posts = $forYou->take(50)->map(function($post) {
  2808. return StatusService::getMastodon($post);
  2809. })
  2810. ->filter(function($post) use($filters) {
  2811. return $post &&
  2812. isset($post['account']) &&
  2813. isset($post['account']['id']) &&
  2814. !in_array($post['account']['id'], $filters);
  2815. })
  2816. ->take(12)
  2817. ->values();
  2818. return $this->json(compact('posts'));
  2819. }
  2820. /**
  2821. * GET /api/v2/statuses/{id}/replies
  2822. *
  2823. *
  2824. * @return array
  2825. */
  2826. public function statusReplies(Request $request, $id)
  2827. {
  2828. abort_if(!$request->user(), 403);
  2829. $this->validate($request, [
  2830. 'limit' => 'int|min:1|max:10',
  2831. 'sort' => 'in:all,newest,popular'
  2832. ]);
  2833. $limit = $request->input('limit', 3);
  2834. $pid = $request->user()->profile_id;
  2835. $status = StatusService::getMastodon($id, false);
  2836. abort_if(!$status, 404);
  2837. if($status['visibility'] == 'private') {
  2838. if($pid != $status['account']['id']) {
  2839. abort_unless(FollowerService::follows($pid, $status['account']['id']), 404);
  2840. }
  2841. }
  2842. $sortBy = $request->input('sort', 'all');
  2843. if($sortBy == 'all' && isset($status['replies_count']) && $status['replies_count'] && $request->has('refresh_cache')) {
  2844. if(!Cache::has('status:replies:all-rc:' . $id)) {
  2845. Cache::forget('status:replies:all:' . $id);
  2846. Cache::put('status:replies:all-rc:' . $id, true, 300);
  2847. }
  2848. }
  2849. if($sortBy == 'all' && !$request->has('cursor')) {
  2850. $ids = Cache::remember('status:replies:all:' . $id, 3600, function() use($id) {
  2851. return DB::table('statuses')
  2852. ->where('in_reply_to_id', $id)
  2853. ->orderBy('id')
  2854. ->cursorPaginate(3);
  2855. });
  2856. } else {
  2857. $ids = DB::table('statuses')
  2858. ->where('in_reply_to_id', $id)
  2859. ->when($sortBy, function($q, $sortBy) {
  2860. if($sortBy === 'all') {
  2861. return $q->orderBy('id');
  2862. }
  2863. if($sortBy === 'newest') {
  2864. return $q->orderByDesc('created_at');
  2865. }
  2866. if($sortBy === 'popular') {
  2867. return $q->orderByDesc('likes_count');
  2868. }
  2869. })
  2870. ->cursorPaginate($limit);
  2871. }
  2872. $data = $ids->map(function($post) use($pid) {
  2873. $status = StatusService::get($post->id, false);
  2874. if(!$status || !isset($status['id'])) {
  2875. return false;
  2876. }
  2877. $status['favourited'] = LikeService::liked($pid, $post->id);
  2878. return $status;
  2879. })
  2880. ->map(function($post) {
  2881. if(isset($post['account']) && isset($post['account']['id'])) {
  2882. $account = AccountService::get($post['account']['id'], true);
  2883. $post['account'] = $account;
  2884. }
  2885. return $post;
  2886. })
  2887. ->filter(function($post) {
  2888. return $post && isset($post['id']) && isset($post['account']) && isset($post['account']['id']);
  2889. })
  2890. ->values();
  2891. $res = [
  2892. 'data' => $data,
  2893. 'next' => $ids->nextPageUrl()
  2894. ];
  2895. return $this->json($res);
  2896. }
  2897. /**
  2898. * GET /api/v2/statuses/{id}/state
  2899. *
  2900. *
  2901. * @return array
  2902. */
  2903. public function statusState(Request $request, $id)
  2904. {
  2905. abort_if(!$request->user(), 403);
  2906. $status = Status::findOrFail($id);
  2907. $pid = $request->user()->profile_id;
  2908. abort_if(!in_array($status->scope, ['public', 'unlisted', 'private']), 404);
  2909. return $this->json(StatusService::getState($status->id, $pid));
  2910. }
  2911. /**
  2912. * GET /api/v1.1/discover/accounts/popular
  2913. *
  2914. *
  2915. * @return array
  2916. */
  2917. public function discoverAccountsPopular(Request $request)
  2918. {
  2919. abort_if(!$request->user(), 403);
  2920. $pid = $request->user()->profile_id;
  2921. $ids = Cache::remember('api:v1.1:discover:accounts:popular', 86400, function() {
  2922. return DB::table('profiles')
  2923. ->where('is_private', false)
  2924. ->whereNull('status')
  2925. ->orderByDesc('profiles.followers_count')
  2926. ->limit(20)
  2927. ->get();
  2928. });
  2929. $ids = $ids->map(function($profile) {
  2930. return AccountService::get($profile->id, true);
  2931. })
  2932. ->filter(function($profile) use($pid) {
  2933. return $profile && isset($profile['id']);
  2934. })
  2935. ->filter(function($profile) use($pid) {
  2936. return $profile['id'] != $pid;
  2937. })
  2938. ->map(function($profile) {
  2939. $ids = collect(ProfileStatusService::get($profile['id'], 0, 9))
  2940. ->map(function($id) {
  2941. return StatusService::get($id, true);
  2942. })
  2943. ->filter(function($post) {
  2944. return $post && isset($post['id']);
  2945. })
  2946. ->take(3);
  2947. $profile['recent_posts'] = $ids;
  2948. return $profile;
  2949. })
  2950. ->take(6)
  2951. ->values();
  2952. return $this->json($ids);
  2953. }
  2954. /**
  2955. * GET /api/v1/preferences
  2956. *
  2957. *
  2958. * @return array
  2959. */
  2960. public function getPreferences(Request $request)
  2961. {
  2962. abort_if(!$request->user(), 403);
  2963. $pid = $request->user()->profile_id;
  2964. $account = AccountService::get($pid);
  2965. return $this->json([
  2966. 'posting:default:visibility' => $account['locked'] ? 'private' : 'public',
  2967. 'posting:default:sensitive' => false,
  2968. 'posting:default:language' => null,
  2969. 'reading:expand:media' => 'default',
  2970. 'reading:expand:spoilers' => false
  2971. ]);
  2972. }
  2973. /**
  2974. * GET /api/v1/trends
  2975. *
  2976. *
  2977. * @return array
  2978. */
  2979. public function getTrends(Request $request)
  2980. {
  2981. abort_if(!$request->user(), 403);
  2982. return $this->json([]);
  2983. }
  2984. /**
  2985. * GET /api/v1/announcements
  2986. *
  2987. *
  2988. * @return array
  2989. */
  2990. public function getAnnouncements(Request $request)
  2991. {
  2992. abort_if(!$request->user(), 403);
  2993. return $this->json([]);
  2994. }
  2995. /**
  2996. * GET /api/v1/markers
  2997. *
  2998. *
  2999. * @return array
  3000. */
  3001. public function getMarkers(Request $request)
  3002. {
  3003. abort_if(!$request->user(), 403);
  3004. $type = $request->input('timeline');
  3005. if(is_array($type)) {
  3006. $type = $type[0];
  3007. }
  3008. if(!$type || !in_array($type, ['home', 'notifications'])) {
  3009. return $this->json([]);
  3010. }
  3011. $pid = $request->user()->profile_id;
  3012. return $this->json(MarkerService::get($pid, $type));
  3013. }
  3014. /**
  3015. * POST /api/v1/markers
  3016. *
  3017. *
  3018. * @return array
  3019. */
  3020. public function setMarkers(Request $request)
  3021. {
  3022. abort_if(!$request->user(), 403);
  3023. $pid = $request->user()->profile_id;
  3024. $home = $request->input('home.last_read_id');
  3025. $notifications = $request->input('notifications.last_read_id');
  3026. if($home) {
  3027. return $this->json(MarkerService::set($pid, 'home', $home));
  3028. }
  3029. if($notifications) {
  3030. return $this->json(MarkerService::set($pid, 'notifications', $notifications));
  3031. }
  3032. return $this->json([]);
  3033. }
  3034. }