ApiV1Controller.php 79 KB

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