1
0

ApiV1Controller.php 92 KB

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