ApiV1Controller.php 91 KB

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