ApiV1Controller.php 76 KB

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