ApiV1Controller.php 89 KB

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