ApiV1Controller.php 72 KB

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