ApiV1Controller.php 78 KB

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