ApiV1Controller.php 80 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105
  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|max:30',
  196. 'note' => 'nullable|string|max:200',
  197. 'locked' => 'nullable',
  198. 'website' => 'nullable|string|max:120',
  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. if($user->profile->following_count) {
  658. $user->profile->decrement('following_count');
  659. }
  660. FollowRequest::whereFollowerId($user->profile_id)
  661. ->whereFollowingId($target->id)
  662. ->delete();
  663. Follower::whereProfileId($user->profile_id)
  664. ->whereFollowingId($target->id)
  665. ->delete();
  666. if($remote == true && config('federation.activitypub.remoteFollow') == true) {
  667. (new FollowerController())->sendUndoFollow($user->profile, $target);
  668. }
  669. RelationshipService::refresh($user->profile_id, $target->id);
  670. Cache::forget('profile:following:'.$target->id);
  671. Cache::forget('profile:followers:'.$target->id);
  672. Cache::forget('profile:following:'.$user->profile_id);
  673. Cache::forget('profile:followers:'.$user->profile_id);
  674. Cache::forget('api:local:exp:rec:'.$user->profile_id);
  675. Cache::forget('user:account:id:'.$target->user_id);
  676. Cache::forget('user:account:id:'.$user->id);
  677. Cache::forget('profile:follower_count:'.$target->id);
  678. Cache::forget('profile:follower_count:'.$user->profile_id);
  679. Cache::forget('profile:following_count:'.$target->id);
  680. Cache::forget('profile:following_count:'.$user->profile_id);
  681. AccountService::del($user->profile_id);
  682. AccountService::del($target->id);
  683. $res = RelationshipService::get($user->profile_id, $target->id);
  684. return $this->json($res);
  685. }
  686. /**
  687. * GET /api/v1/accounts/relationships
  688. *
  689. * @param array|integer $id
  690. *
  691. * @return \App\Services\RelationshipService
  692. */
  693. public function accountRelationshipsById(Request $request)
  694. {
  695. abort_if(!$request->user(), 403);
  696. $this->validate($request, [
  697. 'id' => 'required|array|min:1|max:20',
  698. 'id.*' => 'required|integer|min:1|max:' . PHP_INT_MAX
  699. ]);
  700. $pid = $request->user()->profile_id ?? $request->user()->profile->id;
  701. $res = collect($request->input('id'))
  702. ->filter(function($id) use($pid) {
  703. return $id != $pid;
  704. })
  705. ->map(function($id) use($pid) {
  706. return RelationshipService::get($pid, $id);
  707. });
  708. return $this->json($res);
  709. }
  710. /**
  711. * GET /api/v1/accounts/search
  712. *
  713. *
  714. *
  715. * @return \App\Transformer\Api\AccountTransformer
  716. */
  717. public function accountSearch(Request $request)
  718. {
  719. abort_if(!$request->user(), 403);
  720. $this->validate($request, [
  721. 'q' => 'required|string|min:1|max:255',
  722. 'limit' => 'nullable|integer|min:1|max:40',
  723. 'resolve' => 'nullable'
  724. ]);
  725. $user = $request->user();
  726. $query = $request->input('q');
  727. $limit = $request->input('limit') ?? 20;
  728. $resolve = (bool) $request->input('resolve', false);
  729. $q = '%' . $query . '%';
  730. $profiles = Profile::whereNull('status')
  731. ->where('username', 'like', $q)
  732. ->orWhere('name', 'like', $q)
  733. ->limit($limit)
  734. ->get();
  735. $resource = new Fractal\Resource\Collection($profiles, new AccountTransformer());
  736. $res = $this->fractal->createData($resource)->toArray();
  737. return $this->json($res);
  738. }
  739. /**
  740. * GET /api/v1/blocks
  741. *
  742. *
  743. *
  744. * @return \App\Transformer\Api\AccountTransformer
  745. */
  746. public function accountBlocks(Request $request)
  747. {
  748. abort_if(!$request->user(), 403);
  749. $this->validate($request, [
  750. 'limit' => 'nullable|integer|min:1|max:40',
  751. 'page' => 'nullable|integer|min:1|max:10'
  752. ]);
  753. $user = $request->user();
  754. $limit = $request->input('limit') ?? 40;
  755. $blocked = UserFilter::select('filterable_id','filterable_type','filter_type','user_id')
  756. ->whereUserId($user->profile_id)
  757. ->whereFilterableType('App\Profile')
  758. ->whereFilterType('block')
  759. ->simplePaginate($limit)
  760. ->pluck('filterable_id');
  761. $profiles = Profile::findOrFail($blocked);
  762. $resource = new Fractal\Resource\Collection($profiles, new AccountTransformer());
  763. $res = $this->fractal->createData($resource)->toArray();
  764. return $this->json($res);
  765. }
  766. /**
  767. * POST /api/v1/accounts/{id}/block
  768. *
  769. * @param integer $id
  770. *
  771. * @return \App\Transformer\Api\RelationshipTransformer
  772. */
  773. public function accountBlockById(Request $request, $id)
  774. {
  775. abort_if(!$request->user(), 403);
  776. $user = $request->user();
  777. $pid = $user->profile_id ?? $user->profile->id;
  778. if($id == $pid) {
  779. abort(400, 'You cannot block yourself');
  780. }
  781. $profile = Profile::findOrFail($id);
  782. if($profile->user->is_admin == true) {
  783. abort(400, 'You cannot block an admin');
  784. }
  785. Follower::whereProfileId($profile->id)->whereFollowingId($pid)->delete();
  786. Follower::whereProfileId($pid)->whereFollowingId($profile->id)->delete();
  787. Notification::whereProfileId($pid)->whereActorId($profile->id)->delete();
  788. $filter = UserFilter::firstOrCreate([
  789. 'user_id' => $pid,
  790. 'filterable_id' => $profile->id,
  791. 'filterable_type' => 'App\Profile',
  792. 'filter_type' => 'block',
  793. ]);
  794. Cache::forget("user:filter:list:$pid");
  795. Cache::forget("api:local:exp:rec:$pid");
  796. RelationshipService::refresh($pid, $id);
  797. $resource = new Fractal\Resource\Item($profile, new RelationshipTransformer());
  798. $res = $this->fractal->createData($resource)->toArray();
  799. return $this->json($res);
  800. }
  801. /**
  802. * POST /api/v1/accounts/{id}/unblock
  803. *
  804. * @param integer $id
  805. *
  806. * @return \App\Transformer\Api\RelationshipTransformer
  807. */
  808. public function accountUnblockById(Request $request, $id)
  809. {
  810. abort_if(!$request->user(), 403);
  811. $user = $request->user();
  812. $pid = $user->profile_id ?? $user->profile->id;
  813. if($id == $pid) {
  814. abort(400, 'You cannot unblock yourself');
  815. }
  816. $profile = Profile::findOrFail($id);
  817. UserFilter::whereUserId($pid)
  818. ->whereFilterableId($profile->id)
  819. ->whereFilterableType('App\Profile')
  820. ->whereFilterType('block')
  821. ->delete();
  822. Cache::forget("user:filter:list:$pid");
  823. Cache::forget("api:local:exp:rec:$pid");
  824. RelationshipService::refresh($pid, $id);
  825. $resource = new Fractal\Resource\Item($profile, new RelationshipTransformer());
  826. $res = $this->fractal->createData($resource)->toArray();
  827. return $this->json($res);
  828. }
  829. /**
  830. * GET /api/v1/custom_emojis
  831. *
  832. * Return custom emoji
  833. *
  834. * @return array
  835. */
  836. public function customEmojis()
  837. {
  838. return response(CustomEmojiService::all())->header('Content-Type', 'application/json');
  839. }
  840. /**
  841. * GET /api/v1/domain_blocks
  842. *
  843. * Return empty array
  844. *
  845. * @return array
  846. */
  847. public function accountDomainBlocks(Request $request)
  848. {
  849. abort_if(!$request->user(), 403);
  850. return response()->json([]);
  851. }
  852. /**
  853. * GET /api/v1/endorsements
  854. *
  855. * Return empty array
  856. *
  857. * @return array
  858. */
  859. public function accountEndorsements(Request $request)
  860. {
  861. abort_if(!$request->user(), 403);
  862. return response()->json([]);
  863. }
  864. /**
  865. * GET /api/v1/favourites
  866. *
  867. * Returns collection of liked statuses
  868. *
  869. * @return \App\Transformer\Api\StatusTransformer
  870. */
  871. public function accountFavourites(Request $request)
  872. {
  873. abort_if(!$request->user(), 403);
  874. $this->validate($request, [
  875. 'limit' => 'sometimes|integer|min:1|max:20'
  876. ]);
  877. $user = $request->user();
  878. $maxId = $request->input('max_id');
  879. $minId = $request->input('min_id');
  880. $limit = $request->input('limit') ?? 10;
  881. $res = Like::whereProfileId($user->profile_id)
  882. ->when($maxId, function($q, $maxId) {
  883. return $q->where('id', '<', $maxId);
  884. })
  885. ->when($minId, function($q, $minId) {
  886. return $q->where('id', '>', $minId);
  887. })
  888. ->orderByDesc('id')
  889. ->limit($limit)
  890. ->get()
  891. ->map(function($like) {
  892. $status = StatusService::getMastodon($like['status_id'], false);
  893. $status['like_id'] = $like->id;
  894. $status['liked_at'] = str_replace('+00:00', 'Z', $like->created_at->format(DATE_RFC3339_EXTENDED));
  895. return $status;
  896. })
  897. ->filter(function($status) {
  898. return $status && isset($status['id'], $status['like_id']);
  899. })
  900. ->values();
  901. if($res->count()) {
  902. $ids = $res->map(function($status) {
  903. return $status['like_id'];
  904. });
  905. $max = $ids->max();
  906. $min = $ids->min();
  907. $baseUrl = config('app.url') . '/api/v1/favourites?limit=' . $limit . '&';
  908. $link = '<'.$baseUrl.'max_id='.$max.'>; rel="next",<'.$baseUrl.'min_id='.$min.'>; rel="prev"';
  909. return $this->json($res, 200, ['Link' => $link]);
  910. } else {
  911. return $this->json($res);
  912. }
  913. }
  914. /**
  915. * POST /api/v1/statuses/{id}/favourite
  916. *
  917. * @param integer $id
  918. *
  919. * @return \App\Transformer\Api\StatusTransformer
  920. */
  921. public function statusFavouriteById(Request $request, $id)
  922. {
  923. abort_if(!$request->user(), 403);
  924. $user = $request->user();
  925. $status = StatusService::getMastodon($id, false);
  926. abort_unless($status, 400);
  927. $spid = $status['account']['id'];
  928. if($spid !== $user->profile_id) {
  929. if($status['visibility'] == 'private') {
  930. abort_if(!FollowerService::follows($user->profile_id, $spid), 403);
  931. } else {
  932. abort_if(!in_array($status['visibility'], ['public','unlisted']), 403);
  933. }
  934. }
  935. abort_if(
  936. Like::whereProfileId($user->profile_id)
  937. ->where('created_at', '>', now()->subDay())
  938. ->count() >= Like::MAX_PER_DAY,
  939. 429
  940. );
  941. $like = Like::firstOrCreate([
  942. 'profile_id' => $user->profile_id,
  943. 'status_id' => $status['id']
  944. ]);
  945. if($like->wasRecentlyCreated == true) {
  946. $like->status_profile_id = $spid;
  947. $like->is_comment = !empty($status['in_reply_to_id']);
  948. $like->save();
  949. Status::findOrFail($status['id'])->update([
  950. 'favourites_count' => ($status['favourites_count'] ?? 0) + 1
  951. ]);
  952. LikePipeline::dispatch($like);
  953. }
  954. $status['favourited'] = true;
  955. $status['favourites_count'] = $status['favourites_count'] + 1;
  956. return $this->json($status);
  957. }
  958. /**
  959. * POST /api/v1/statuses/{id}/unfavourite
  960. *
  961. * @param integer $id
  962. *
  963. * @return \App\Transformer\Api\StatusTransformer
  964. */
  965. public function statusUnfavouriteById(Request $request, $id)
  966. {
  967. abort_if(!$request->user(), 403);
  968. $user = $request->user();
  969. $status = Status::findOrFail($id);
  970. if($status->profile_id !== $user->profile_id) {
  971. if($status->scope == 'private') {
  972. abort_if(!$status->profile->followedBy($user->profile), 403);
  973. } else {
  974. abort_if(!in_array($status->scope, ['public','unlisted']), 403);
  975. }
  976. }
  977. $like = Like::whereProfileId($user->profile_id)
  978. ->whereStatusId($status->id)
  979. ->first();
  980. if($like) {
  981. $like->forceDelete();
  982. $status->likes_count = $status->likes()->count();
  983. $status->save();
  984. }
  985. StatusService::del($status->id);
  986. $res = StatusService::getMastodon($status->id, false);
  987. $res['favourited'] = false;
  988. return $this->json($res);
  989. }
  990. /**
  991. * GET /api/v1/filters
  992. *
  993. * Return empty response since we filter server side
  994. *
  995. * @return array
  996. */
  997. public function accountFilters(Request $request)
  998. {
  999. abort_if(!$request->user(), 403);
  1000. return response()->json([]);
  1001. }
  1002. /**
  1003. * GET /api/v1/follow_requests
  1004. *
  1005. * Return array of Accounts that have sent follow requests
  1006. *
  1007. * @return \App\Transformer\Api\AccountTransformer
  1008. */
  1009. public function accountFollowRequests(Request $request)
  1010. {
  1011. abort_if(!$request->user(), 403);
  1012. $this->validate($request, [
  1013. 'limit' => 'sometimes|integer|min:1|max:100'
  1014. ]);
  1015. $user = $request->user();
  1016. $res = FollowRequest::whereFollowingId($user->profile->id)
  1017. ->limit($request->input('limit', 40))
  1018. ->pluck('follower_id')
  1019. ->map(function($id) {
  1020. return AccountService::getMastodon($id, true);
  1021. })
  1022. ->filter(function($acct) {
  1023. return $acct && isset($acct['id']);
  1024. })
  1025. ->values();
  1026. return $this->json($res);
  1027. }
  1028. /**
  1029. * POST /api/v1/follow_requests/{id}/authorize
  1030. *
  1031. * @param integer $id
  1032. *
  1033. * @return null
  1034. */
  1035. public function accountFollowRequestAccept(Request $request, $id)
  1036. {
  1037. abort_if(!$request->user(), 403);
  1038. $pid = $request->user()->profile_id;
  1039. $target = AccountService::getMastodon($id);
  1040. if(!$target) {
  1041. return response()->json(['error' => 'Record not found'], 404);
  1042. }
  1043. $followRequest = FollowRequest::whereFollowingId($pid)->whereFollowerId($id)->first();
  1044. if(!$followRequest) {
  1045. return response()->json(['error' => 'Record not found'], 404);
  1046. }
  1047. $follower = $followRequest->follower;
  1048. $follow = new Follower();
  1049. $follow->profile_id = $follower->id;
  1050. $follow->following_id = $pid;
  1051. $follow->save();
  1052. $profile = Profile::findOrFail($pid);
  1053. $profile->followers_count++;
  1054. $profile->save();
  1055. AccountService::del($profile->id);
  1056. $profile = Profile::findOrFail($follower->id);
  1057. $profile->following_count++;
  1058. $profile->save();
  1059. AccountService::del($profile->id);
  1060. if($follower->domain != null && $follower->private_key === null) {
  1061. FollowAcceptPipeline::dispatch($followRequest);
  1062. } else {
  1063. FollowPipeline::dispatch($follow);
  1064. $followRequest->delete();
  1065. }
  1066. RelationshipService::refresh($pid, $id);
  1067. $res = RelationshipService::get($pid, $id);
  1068. $res['followed_by'] = true;
  1069. return $this->json($res);
  1070. }
  1071. /**
  1072. * POST /api/v1/follow_requests/{id}/reject
  1073. *
  1074. * @param integer $id
  1075. *
  1076. * @return null
  1077. */
  1078. public function accountFollowRequestReject(Request $request, $id)
  1079. {
  1080. abort_if(!$request->user(), 403);
  1081. $pid = $request->user()->profile_id;
  1082. $target = AccountService::getMastodon($id);
  1083. if(!$target) {
  1084. return response()->json(['error' => 'Record not found'], 404);
  1085. }
  1086. $followRequest = FollowRequest::whereFollowingId($pid)->whereFollowerId($id)->first();
  1087. if(!$followRequest) {
  1088. return response()->json(['error' => 'Record not found'], 404);
  1089. }
  1090. $follower = $followRequest->follower;
  1091. if($follower->domain != null && $follower->private_key === null) {
  1092. FollowRejectPipeline::dispatch($followRequest);
  1093. } else {
  1094. $followRequest->delete();
  1095. }
  1096. RelationshipService::refresh($pid, $id);
  1097. $res = RelationshipService::get($pid, $id);
  1098. return $this->json($res);
  1099. }
  1100. /**
  1101. * GET /api/v1/suggestions
  1102. *
  1103. * Return empty array as we don't support suggestions
  1104. *
  1105. * @return null
  1106. */
  1107. public function accountSuggestions(Request $request)
  1108. {
  1109. abort_if(!$request->user(), 403);
  1110. // todo
  1111. return response()->json([]);
  1112. }
  1113. /**
  1114. * GET /api/v1/instance
  1115. *
  1116. * Information about the server.
  1117. *
  1118. * @return Instance
  1119. */
  1120. public function instance(Request $request)
  1121. {
  1122. $res = Cache::remember('api:v1:instance-data-response-v0', 1800, function () {
  1123. $contact = Cache::remember('api:v1:instance-data:contact', 604800, function () {
  1124. $admin = User::whereIsAdmin(true)->first();
  1125. return $admin && isset($admin->profile_id) ?
  1126. AccountService::getMastodon($admin->profile_id, true) :
  1127. null;
  1128. });
  1129. $stats = Cache::remember('api:v1:instance-data:stats', 43200, function () {
  1130. return [
  1131. 'user_count' => User::count(),
  1132. 'status_count' => Status::whereNull('uri')->count(),
  1133. 'domain_count' => Instance::count(),
  1134. ];
  1135. });
  1136. $rules = Cache::remember('api:v1:instance-data:rules', 604800, function () {
  1137. return config_cache('app.rules') ?
  1138. collect(json_decode(config_cache('app.rules'), true))
  1139. ->map(function($rule, $key) {
  1140. $id = $key + 1;
  1141. return [
  1142. 'id' => "{$id}",
  1143. 'text' => $rule
  1144. ];
  1145. })
  1146. ->toArray() : [];
  1147. });
  1148. return [
  1149. 'uri' => config('pixelfed.domain.app'),
  1150. 'title' => config('app.name'),
  1151. 'short_description' => config_cache('app.short_description'),
  1152. 'description' => config_cache('app.description'),
  1153. 'email' => config('instance.email'),
  1154. 'version' => '2.7.2 (compatible; Pixelfed ' . config('pixelfed.version') .')',
  1155. 'urls' => [
  1156. 'streaming_api' => 'wss://' . config('pixelfed.domain.app')
  1157. ],
  1158. 'stats' => $stats,
  1159. 'thumbnail' => url('img/pixelfed-icon-color.png'),
  1160. 'languages' => [config('app.locale')],
  1161. 'registrations' => (bool) config_cache('pixelfed.open_registration'),
  1162. 'approval_required' => false,
  1163. 'contact_account' => $contact,
  1164. 'rules' => $rules
  1165. ];
  1166. });
  1167. return $this->json($res);
  1168. }
  1169. /**
  1170. * GET /api/v1/lists
  1171. *
  1172. * Return empty array as we don't support lists
  1173. *
  1174. * @return null
  1175. */
  1176. public function accountLists(Request $request)
  1177. {
  1178. abort_if(!$request->user(), 403);
  1179. return response()->json([]);
  1180. }
  1181. /**
  1182. * GET /api/v1/accounts/{id}/lists
  1183. *
  1184. * @param integer $id
  1185. *
  1186. * @return null
  1187. */
  1188. public function accountListsById(Request $request, $id)
  1189. {
  1190. abort_if(!$request->user(), 403);
  1191. return response()->json([]);
  1192. }
  1193. /**
  1194. * POST /api/v1/media
  1195. *
  1196. *
  1197. * @return MediaTransformer
  1198. */
  1199. public function mediaUpload(Request $request)
  1200. {
  1201. abort_if(!$request->user(), 403);
  1202. $this->validate($request, [
  1203. 'file.*' => function() {
  1204. return [
  1205. 'required',
  1206. 'mimetypes:' . config_cache('pixelfed.media_types'),
  1207. 'max:' . config_cache('pixelfed.max_photo_size'),
  1208. ];
  1209. },
  1210. 'filter_name' => 'nullable|string|max:24',
  1211. 'filter_class' => 'nullable|alpha_dash|max:24',
  1212. 'description' => 'nullable|string|max:' . config_cache('pixelfed.max_altext_length')
  1213. ]);
  1214. $user = $request->user();
  1215. if($user->last_active_at == null) {
  1216. return [];
  1217. }
  1218. if(empty($request->file('file'))) {
  1219. return response('', 422);
  1220. }
  1221. $limitKey = 'compose:rate-limit:media-upload:' . $user->id;
  1222. $limitTtl = now()->addMinutes(15);
  1223. $limitReached = Cache::remember($limitKey, $limitTtl, function() use($user) {
  1224. $dailyLimit = Media::whereUserId($user->id)->where('created_at', '>', now()->subDays(1))->count();
  1225. return $dailyLimit >= 250;
  1226. });
  1227. abort_if($limitReached == true, 429);
  1228. $profile = $user->profile;
  1229. if(config_cache('pixelfed.enforce_account_limit') == true) {
  1230. $size = Cache::remember($user->storageUsedKey(), now()->addDays(3), function() use($user) {
  1231. return Media::whereUserId($user->id)->sum('size') / 1000;
  1232. });
  1233. $limit = (int) config_cache('pixelfed.max_account_size');
  1234. if ($size >= $limit) {
  1235. abort(403, 'Account size limit reached.');
  1236. }
  1237. }
  1238. $filterClass = in_array($request->input('filter_class'), Filter::classes()) ? $request->input('filter_class') : null;
  1239. $filterName = in_array($request->input('filter_name'), Filter::names()) ? $request->input('filter_name') : null;
  1240. $photo = $request->file('file');
  1241. $mimes = explode(',', config_cache('pixelfed.media_types'));
  1242. if(in_array($photo->getMimeType(), $mimes) == false) {
  1243. abort(403, 'Invalid or unsupported mime type.');
  1244. }
  1245. $storagePath = MediaPathService::get($user, 2);
  1246. $path = $photo->store($storagePath);
  1247. $hash = \hash_file('sha256', $photo);
  1248. $license = null;
  1249. $mime = $photo->getMimeType();
  1250. // if($photo->getMimeType() == 'image/heic') {
  1251. // abort_if(config('image.driver') !== 'imagick', 422, 'Invalid media type');
  1252. // abort_if(!in_array('HEIC', \Imagick::queryformats()), 422, 'Unsupported media type');
  1253. // $oldPath = $path;
  1254. // $path = str_replace('.heic', '.jpg', $path);
  1255. // $mime = 'image/jpeg';
  1256. // \Image::make($photo)->save(storage_path("app/{$path}"));
  1257. // @unlink(storage_path("app/{$oldPath}"));
  1258. // }
  1259. $settings = UserSetting::whereUserId($user->id)->first();
  1260. if($settings && !empty($settings->compose_settings)) {
  1261. $compose = $settings->compose_settings;
  1262. if(isset($compose['default_license']) && $compose['default_license'] != 1) {
  1263. $license = $compose['default_license'];
  1264. }
  1265. }
  1266. abort_if(MediaBlocklistService::exists($hash) == true, 451);
  1267. $media = new Media();
  1268. $media->status_id = null;
  1269. $media->profile_id = $profile->id;
  1270. $media->user_id = $user->id;
  1271. $media->media_path = $path;
  1272. $media->original_sha256 = $hash;
  1273. $media->size = $photo->getSize();
  1274. $media->mime = $mime;
  1275. $media->caption = $request->input('description');
  1276. $media->filter_class = $filterClass;
  1277. $media->filter_name = $filterName;
  1278. if($license) {
  1279. $media->license = $license;
  1280. }
  1281. $media->save();
  1282. switch ($media->mime) {
  1283. case 'image/jpeg':
  1284. case 'image/png':
  1285. ImageOptimize::dispatch($media);
  1286. break;
  1287. case 'video/mp4':
  1288. VideoThumbnail::dispatch($media);
  1289. $preview_url = '/storage/no-preview.png';
  1290. $url = '/storage/no-preview.png';
  1291. break;
  1292. }
  1293. Cache::forget($limitKey);
  1294. $resource = new Fractal\Resource\Item($media, new MediaTransformer());
  1295. $res = $this->fractal->createData($resource)->toArray();
  1296. $res['preview_url'] = $media->url(). '?v=' . time();
  1297. $res['url'] = $media->url(). '?v=' . time();
  1298. return $this->json($res);
  1299. }
  1300. /**
  1301. * PUT /api/v1/media/{id}
  1302. *
  1303. * @param integer $id
  1304. *
  1305. * @return MediaTransformer
  1306. */
  1307. public function mediaUpdate(Request $request, $id)
  1308. {
  1309. abort_if(!$request->user(), 403);
  1310. $this->validate($request, [
  1311. 'description' => 'nullable|string|max:' . config_cache('pixelfed.max_altext_length')
  1312. ]);
  1313. $user = $request->user();
  1314. $media = Media::whereUserId($user->id)
  1315. ->whereNull('status_id')
  1316. ->findOrFail($id);
  1317. $media->caption = $request->input('description');
  1318. $media->save();
  1319. $resource = new Fractal\Resource\Item($media, new MediaTransformer());
  1320. $res = $this->fractal->createData($resource)->toArray();
  1321. return $this->json($res);
  1322. }
  1323. /**
  1324. * GET /api/v1/media/{id}
  1325. *
  1326. * @param integer $id
  1327. *
  1328. * @return MediaTransformer
  1329. */
  1330. public function mediaGet(Request $request, $id)
  1331. {
  1332. abort_if(!$request->user(), 403);
  1333. $user = $request->user();
  1334. $media = Media::whereUserId($user->id)
  1335. ->whereNull('status_id')
  1336. ->findOrFail($id);
  1337. $resource = new Fractal\Resource\Item($media, new MediaTransformer());
  1338. $res = $this->fractal->createData($resource)->toArray();
  1339. return $this->json($res);
  1340. }
  1341. /**
  1342. * POST /api/v2/media
  1343. *
  1344. *
  1345. * @return MediaTransformer
  1346. */
  1347. public function mediaUploadV2(Request $request)
  1348. {
  1349. abort_if(!$request->user(), 403);
  1350. $this->validate($request, [
  1351. 'file.*' => function() {
  1352. return [
  1353. 'required',
  1354. 'mimetypes:' . config_cache('pixelfed.media_types'),
  1355. 'max:' . config_cache('pixelfed.max_photo_size'),
  1356. ];
  1357. },
  1358. 'filter_name' => 'nullable|string|max:24',
  1359. 'filter_class' => 'nullable|alpha_dash|max:24',
  1360. 'description' => 'nullable|string|max:' . config_cache('pixelfed.max_altext_length')
  1361. ]);
  1362. $user = $request->user();
  1363. if($user->last_active_at == null) {
  1364. return [];
  1365. }
  1366. if(empty($request->file('file'))) {
  1367. return response('', 422);
  1368. }
  1369. $limitKey = 'compose:rate-limit:media-upload:' . $user->id;
  1370. $limitTtl = now()->addMinutes(15);
  1371. $limitReached = Cache::remember($limitKey, $limitTtl, function() use($user) {
  1372. $dailyLimit = Media::whereUserId($user->id)->where('created_at', '>', now()->subDays(1))->count();
  1373. return $dailyLimit >= 250;
  1374. });
  1375. abort_if($limitReached == true, 429);
  1376. $profile = $user->profile;
  1377. if(config_cache('pixelfed.enforce_account_limit') == true) {
  1378. $size = Cache::remember($user->storageUsedKey(), now()->addDays(3), function() use($user) {
  1379. return Media::whereUserId($user->id)->sum('size') / 1000;
  1380. });
  1381. $limit = (int) config_cache('pixelfed.max_account_size');
  1382. if ($size >= $limit) {
  1383. abort(403, 'Account size limit reached.');
  1384. }
  1385. }
  1386. $filterClass = in_array($request->input('filter_class'), Filter::classes()) ? $request->input('filter_class') : null;
  1387. $filterName = in_array($request->input('filter_name'), Filter::names()) ? $request->input('filter_name') : null;
  1388. $photo = $request->file('file');
  1389. $mimes = explode(',', config_cache('pixelfed.media_types'));
  1390. if(in_array($photo->getMimeType(), $mimes) == false) {
  1391. abort(403, 'Invalid or unsupported mime type.');
  1392. }
  1393. $storagePath = MediaPathService::get($user, 2);
  1394. $path = $photo->store($storagePath);
  1395. $hash = \hash_file('sha256', $photo);
  1396. $license = null;
  1397. $mime = $photo->getMimeType();
  1398. $settings = UserSetting::whereUserId($user->id)->first();
  1399. if($settings && !empty($settings->compose_settings)) {
  1400. $compose = $settings->compose_settings;
  1401. if(isset($compose['default_license']) && $compose['default_license'] != 1) {
  1402. $license = $compose['default_license'];
  1403. }
  1404. }
  1405. abort_if(MediaBlocklistService::exists($hash) == true, 451);
  1406. $media = new Media();
  1407. $media->status_id = null;
  1408. $media->profile_id = $profile->id;
  1409. $media->user_id = $user->id;
  1410. $media->media_path = $path;
  1411. $media->original_sha256 = $hash;
  1412. $media->size = $photo->getSize();
  1413. $media->mime = $mime;
  1414. $media->caption = $request->input('description');
  1415. $media->filter_class = $filterClass;
  1416. $media->filter_name = $filterName;
  1417. if($license) {
  1418. $media->license = $license;
  1419. }
  1420. $media->save();
  1421. switch ($media->mime) {
  1422. case 'image/jpeg':
  1423. case 'image/png':
  1424. ImageOptimize::dispatch($media);
  1425. break;
  1426. case 'video/mp4':
  1427. VideoThumbnail::dispatch($media);
  1428. $preview_url = '/storage/no-preview.png';
  1429. $url = '/storage/no-preview.png';
  1430. break;
  1431. }
  1432. Cache::forget($limitKey);
  1433. $resource = new Fractal\Resource\Item($media, new MediaTransformer());
  1434. $res = $this->fractal->createData($resource)->toArray();
  1435. $res['preview_url'] = $media->url(). '?v=' . time();
  1436. $res['url'] = null;
  1437. return $this->json($res, 202);
  1438. }
  1439. /**
  1440. * GET /api/v1/mutes
  1441. *
  1442. *
  1443. * @return AccountTransformer
  1444. */
  1445. public function accountMutes(Request $request)
  1446. {
  1447. abort_if(!$request->user(), 403);
  1448. $this->validate($request, [
  1449. 'limit' => 'nullable|integer|min:1|max:40'
  1450. ]);
  1451. $user = $request->user();
  1452. $limit = $request->input('limit') ?? 40;
  1453. $mutes = UserFilter::whereUserId($user->profile_id)
  1454. ->whereFilterableType('App\Profile')
  1455. ->whereFilterType('mute')
  1456. ->simplePaginate($limit)
  1457. ->pluck('filterable_id');
  1458. $accounts = Profile::find($mutes);
  1459. $resource = new Fractal\Resource\Collection($accounts, new AccountTransformer());
  1460. $res = $this->fractal->createData($resource)->toArray();
  1461. return $this->json($res);
  1462. }
  1463. /**
  1464. * POST /api/v1/accounts/{id}/mute
  1465. *
  1466. * @param integer $id
  1467. *
  1468. * @return RelationshipTransformer
  1469. */
  1470. public function accountMuteById(Request $request, $id)
  1471. {
  1472. abort_if(!$request->user(), 403);
  1473. $user = $request->user();
  1474. $pid = $user->profile_id;
  1475. $account = Profile::findOrFail($id);
  1476. $filter = UserFilter::firstOrCreate([
  1477. 'user_id' => $pid,
  1478. 'filterable_id' => $account->id,
  1479. 'filterable_type' => 'App\Profile',
  1480. 'filter_type' => 'mute',
  1481. ]);
  1482. Cache::forget("user:filter:list:$pid");
  1483. Cache::forget("feature:discover:posts:$pid");
  1484. Cache::forget("api:local:exp:rec:$pid");
  1485. RelationshipService::refresh($pid, $id);
  1486. $resource = new Fractal\Resource\Item($account, new RelationshipTransformer());
  1487. $res = $this->fractal->createData($resource)->toArray();
  1488. return $this->json($res);
  1489. }
  1490. /**
  1491. * POST /api/v1/accounts/{id}/unmute
  1492. *
  1493. * @param integer $id
  1494. *
  1495. * @return RelationshipTransformer
  1496. */
  1497. public function accountUnmuteById(Request $request, $id)
  1498. {
  1499. abort_if(!$request->user(), 403);
  1500. $user = $request->user();
  1501. $pid = $user->profile_id;
  1502. $account = Profile::findOrFail($id);
  1503. $filter = UserFilter::whereUserId($pid)
  1504. ->whereFilterableId($account->id)
  1505. ->whereFilterableType('App\Profile')
  1506. ->whereFilterType('mute')
  1507. ->first();
  1508. if($filter) {
  1509. $filter->delete();
  1510. Cache::forget("user:filter:list:$pid");
  1511. Cache::forget("feature:discover:posts:$pid");
  1512. Cache::forget("api:local:exp:rec:$pid");
  1513. RelationshipService::refresh($pid, $id);
  1514. }
  1515. $resource = new Fractal\Resource\Item($account, new RelationshipTransformer());
  1516. $res = $this->fractal->createData($resource)->toArray();
  1517. return $this->json($res);
  1518. }
  1519. /**
  1520. * GET /api/v1/notifications
  1521. *
  1522. *
  1523. * @return NotificationTransformer
  1524. */
  1525. public function accountNotifications(Request $request)
  1526. {
  1527. abort_if(!$request->user(), 403);
  1528. $this->validate($request, [
  1529. 'limit' => 'nullable|integer|min:1|max:100',
  1530. 'min_id' => 'nullable|integer|min:1|max:'.PHP_INT_MAX,
  1531. 'max_id' => 'nullable|integer|min:1|max:'.PHP_INT_MAX,
  1532. 'since_id' => 'nullable|integer|min:1|max:'.PHP_INT_MAX,
  1533. ]);
  1534. $pid = $request->user()->profile_id;
  1535. $limit = $request->input('limit', 20);
  1536. $since = $request->input('since_id');
  1537. $min = $request->input('min_id');
  1538. $max = $request->input('max_id');
  1539. if(!$since && !$min && !$max) {
  1540. $min = 1;
  1541. }
  1542. $maxId = null;
  1543. $minId = null;
  1544. if($max) {
  1545. $res = NotificationService::getMaxMastodon($pid, $max, $limit);
  1546. $ids = NotificationService::getRankedMaxId($pid, $max, $limit);
  1547. if(!empty($ids)) {
  1548. $maxId = max($ids);
  1549. $minId = min($ids);
  1550. }
  1551. } else {
  1552. $res = NotificationService::getMinMastodon($pid, $min ?? $since, $limit);
  1553. $ids = NotificationService::getRankedMinId($pid, $min ?? $since, $limit);
  1554. if(!empty($ids)) {
  1555. $maxId = max($ids);
  1556. $minId = min($ids);
  1557. }
  1558. }
  1559. if(empty($res) && !Cache::has('pf:services:notifications:hasSynced:'.$pid)) {
  1560. Cache::put('pf:services:notifications:hasSynced:'.$pid, 1, 1209600);
  1561. NotificationService::warmCache($pid, 400, true);
  1562. }
  1563. $baseUrl = config('app.url') . '/api/v1/notifications?limit=' . $limit . '&';
  1564. if($minId == $maxId) {
  1565. $minId = null;
  1566. }
  1567. if($maxId) {
  1568. $link = '<'.$baseUrl.'max_id='.$maxId.'>; rel="next"';
  1569. }
  1570. if($minId) {
  1571. $link = '<'.$baseUrl.'min_id='.$minId.'>; rel="prev"';
  1572. }
  1573. if($maxId && $minId) {
  1574. $link = '<'.$baseUrl.'max_id='.$maxId.'>; rel="next",<'.$baseUrl.'min_id='.$minId.'>; rel="prev"';
  1575. }
  1576. $headers = isset($link) ? ['Link' => $link] : [];
  1577. return $this->json($res, 200, $headers);
  1578. }
  1579. /**
  1580. * GET /api/v1/timelines/home
  1581. *
  1582. *
  1583. * @return StatusTransformer
  1584. */
  1585. public function timelineHome(Request $request)
  1586. {
  1587. $this->validate($request,[
  1588. 'page' => 'nullable|integer|max:40',
  1589. 'min_id' => 'nullable|integer|min:0|max:' . PHP_INT_MAX,
  1590. 'max_id' => 'nullable|integer|min:0|max:' . PHP_INT_MAX,
  1591. 'limit' => 'nullable|integer|max:100'
  1592. ]);
  1593. $page = $request->input('page');
  1594. $min = $request->input('min_id');
  1595. $max = $request->input('max_id');
  1596. $limit = $request->input('limit') ?? 20;
  1597. $pid = $request->user()->profile_id;
  1598. $following = Cache::remember('profile:following:'.$pid, now()->addMinutes(1440), function() use($pid) {
  1599. $following = Follower::whereProfileId($pid)->pluck('following_id');
  1600. return $following->push($pid)->toArray();
  1601. });
  1602. if($min || $max) {
  1603. $dir = $min ? '>' : '<';
  1604. $id = $min ?? $max;
  1605. $res = Status::select(
  1606. 'id',
  1607. 'profile_id',
  1608. 'type',
  1609. 'visibility',
  1610. 'created_at'
  1611. )
  1612. ->whereIn('type', ['photo', 'photo:album', 'video', 'video:album', 'photo:video:album'])
  1613. ->where('id', $dir, $id)
  1614. ->whereIn('profile_id', $following)
  1615. ->whereIn('visibility',['public', 'unlisted', 'private'])
  1616. ->latest()
  1617. ->take(($limit * 2))
  1618. ->get()
  1619. ->map(function($s) use($pid) {
  1620. $status = StatusService::getMastodon($s['id'], false);
  1621. if(!$status || !isset($status['account']) || !isset($status['account']['id'])) {
  1622. return false;
  1623. }
  1624. if($pid) {
  1625. $status['favourited'] = (bool) LikeService::liked($pid, $s['id']);
  1626. $status['reblogged'] = (bool) ReblogService::get($pid, $status['id']);
  1627. }
  1628. return $status;
  1629. })
  1630. ->filter(function($status) {
  1631. return $status && isset($status['account']);
  1632. })
  1633. ->take($limit)
  1634. ->values();
  1635. } else {
  1636. $res = Status::select(
  1637. 'id',
  1638. 'profile_id',
  1639. 'type',
  1640. 'visibility',
  1641. 'created_at'
  1642. )
  1643. ->whereIn('type', ['photo', 'photo:album', 'video', 'video:album', 'photo:video:album'])
  1644. ->whereIn('profile_id', $following)
  1645. ->whereIn('visibility',['public', 'unlisted', 'private'])
  1646. ->latest()
  1647. ->take(($limit * 2))
  1648. ->get()
  1649. ->map(function($s) use($pid) {
  1650. $status = StatusService::getMastodon($s['id'], false);
  1651. if(!$status || !isset($status['account']) || !isset($status['account']['id'])) {
  1652. return false;
  1653. }
  1654. if($pid) {
  1655. $status['favourited'] = (bool) LikeService::liked($pid, $s['id']);
  1656. $status['reblogged'] = (bool) ReblogService::get($pid, $status['id']);
  1657. }
  1658. return $status;
  1659. })
  1660. ->filter(function($status) {
  1661. return $status && isset($status['account']);
  1662. })
  1663. ->take($limit)
  1664. ->values();
  1665. }
  1666. $baseUrl = config('app.url') . '/api/v1/timelines/home?limit=' . $limit . '&';
  1667. $minId = $res->map(function($s) {
  1668. return ['id' => $s['id']];
  1669. })->min('id');
  1670. $maxId = $res->map(function($s) {
  1671. return ['id' => $s['id']];
  1672. })->max('id');
  1673. if($minId == $maxId) {
  1674. $minId = null;
  1675. }
  1676. if($maxId) {
  1677. $link = '<'.$baseUrl.'max_id='.$maxId.'>; rel="next"';
  1678. }
  1679. if($minId) {
  1680. $link = '<'.$baseUrl.'min_id='.$minId.'>; rel="prev"';
  1681. }
  1682. if($maxId && $minId) {
  1683. $link = '<'.$baseUrl.'max_id='.$maxId.'>; rel="next",<'.$baseUrl.'min_id='.$minId.'>; rel="prev"';
  1684. }
  1685. $headers = isset($link) ? ['Link' => $link] : [];
  1686. return $this->json($res->toArray(), 200, $headers);
  1687. }
  1688. /**
  1689. * GET /api/v1/timelines/public
  1690. *
  1691. *
  1692. * @return StatusTransformer
  1693. */
  1694. public function timelinePublic(Request $request)
  1695. {
  1696. $this->validate($request,[
  1697. 'min_id' => 'nullable|integer|min:0|max:' . PHP_INT_MAX,
  1698. 'max_id' => 'nullable|integer|min:0|max:' . PHP_INT_MAX,
  1699. 'limit' => 'nullable|integer|max:100',
  1700. 'remote' => 'sometimes',
  1701. 'local' => 'sometimes'
  1702. ]);
  1703. $min = $request->input('min_id');
  1704. $max = $request->input('max_id');
  1705. $limit = $request->input('limit') ?? 20;
  1706. $user = $request->user();
  1707. $remote = ($request->has('remote') && $request->input('remote') == true) || ($request->filled('local') && $request->input('local') != true);
  1708. $filtered = $user ? UserFilterService::filters($user->profile_id) : [];
  1709. if((!$request->has('local') || $remote) && config('instance.timeline.network.cached')) {
  1710. Cache::remember('api:v1:timelines:network:cache_check', 10368000, function() {
  1711. if(NetworkTimelineService::count() == 0) {
  1712. NetworkTimelineService::warmCache(true, config('instance.timeline.network.cache_dropoff'));
  1713. }
  1714. });
  1715. if ($max) {
  1716. $feed = NetworkTimelineService::getRankedMaxId($max, $limit + 5);
  1717. } else if ($min) {
  1718. $feed = NetworkTimelineService::getRankedMinId($min, $limit + 5);
  1719. } else {
  1720. $feed = NetworkTimelineService::get(0, $limit + 5);
  1721. }
  1722. } else {
  1723. Cache::remember('api:v1:timelines:public:cache_check', 10368000, function() {
  1724. if(PublicTimelineService::count() == 0) {
  1725. PublicTimelineService::warmCache(true, 400);
  1726. }
  1727. });
  1728. if ($max) {
  1729. $feed = PublicTimelineService::getRankedMaxId($max, $limit + 5);
  1730. } else if ($min) {
  1731. $feed = PublicTimelineService::getRankedMinId($min, $limit + 5);
  1732. } else {
  1733. $feed = PublicTimelineService::get(0, $limit + 5);
  1734. }
  1735. }
  1736. $res = collect($feed)
  1737. ->filter(function($k) use($min, $max) {
  1738. if(!$min && !$max) {
  1739. return true;
  1740. }
  1741. if($min) {
  1742. return $min != $k;
  1743. }
  1744. if($max) {
  1745. return $max != $k;
  1746. }
  1747. })
  1748. ->map(function($k) use($user) {
  1749. $status = StatusService::getMastodon($k);
  1750. if(!$status || !isset($status['account']) || !isset($status['account']['id'])) {
  1751. return false;
  1752. }
  1753. if($user) {
  1754. $status['favourited'] = (bool) LikeService::liked($user->profile_id, $k);
  1755. $status['reblogged'] = (bool) ReblogService::get($user->profile_id, $status['id']);
  1756. }
  1757. return $status;
  1758. })
  1759. ->filter(function($s) use($filtered) {
  1760. return $s && isset($s['account']) && in_array($s['account']['id'], $filtered) == false;
  1761. })
  1762. ->take($limit)
  1763. ->values();
  1764. $baseUrl = config('app.url') . '/api/v1/timelines/public?limit=' . $limit . '&';
  1765. if($remote) {
  1766. $baseUrl .= 'remote=1&';
  1767. }
  1768. $minId = $res->map(function($s) {
  1769. return ['id' => $s['id']];
  1770. })->min('id');
  1771. $maxId = $res->map(function($s) {
  1772. return ['id' => $s['id']];
  1773. })->max('id');
  1774. if($minId == $maxId) {
  1775. $minId = null;
  1776. }
  1777. if($maxId) {
  1778. $link = '<'.$baseUrl.'max_id='.$maxId.'>; rel="next"';
  1779. }
  1780. if($minId) {
  1781. $link = '<'.$baseUrl.'min_id='.$minId.'>; rel="prev"';
  1782. }
  1783. if($maxId && $minId) {
  1784. $link = '<'.$baseUrl.'max_id='.$maxId.'>; rel="next",<'.$baseUrl.'min_id='.$minId.'>; rel="prev"';
  1785. }
  1786. $headers = isset($link) ? ['Link' => $link] : [];
  1787. return $this->json($res->toArray(), 200, $headers);
  1788. }
  1789. /**
  1790. * GET /api/v1/conversations
  1791. *
  1792. * Not implemented
  1793. *
  1794. * @return array
  1795. */
  1796. public function conversations(Request $request)
  1797. {
  1798. abort_if(!$request->user(), 403);
  1799. $this->validate($request, [
  1800. 'limit' => 'min:1|max:40',
  1801. 'scope' => 'nullable|in:inbox,sent,requests'
  1802. ]);
  1803. $limit = $request->input('limit', 20);
  1804. $scope = $request->input('scope', 'inbox');
  1805. $pid = $request->user()->profile_id;
  1806. if(config('database.default') == 'pgsql') {
  1807. $dms = DirectMessage::when($scope === 'inbox', function($q, $scope) use($pid) {
  1808. return $q->whereIsHidden(false)->where('to_id', $pid)->orWhere('from_id', $pid);
  1809. })
  1810. ->when($scope === 'sent', function($q, $scope) use($pid) {
  1811. return $q->whereFromId($pid)->groupBy(['to_id', 'id']);
  1812. })
  1813. ->when($scope === 'requests', function($q, $scope) use($pid) {
  1814. return $q->whereToId($pid)->whereIsHidden(true);
  1815. });
  1816. } else {
  1817. $dms = Conversation::when($scope === 'inbox', function($q, $scope) use($pid) {
  1818. return $q->whereIsHidden(false)
  1819. ->where('to_id', $pid)
  1820. ->orWhere('from_id', $pid)
  1821. ->orderByDesc('status_id')
  1822. ->groupBy(['to_id', 'from_id']);
  1823. })
  1824. ->when($scope === 'sent', function($q, $scope) use($pid) {
  1825. return $q->whereFromId($pid)->groupBy('to_id');
  1826. })
  1827. ->when($scope === 'requests', function($q, $scope) use($pid) {
  1828. return $q->whereToId($pid)->whereIsHidden(true);
  1829. });
  1830. }
  1831. $dms = $dms->orderByDesc('status_id')
  1832. ->simplePaginate($limit)
  1833. ->map(function($dm) use($pid) {
  1834. $from = $pid == $dm->to_id ? $dm->from_id : $dm->to_id;
  1835. $res = [
  1836. 'id' => $dm->id,
  1837. 'unread' => false,
  1838. 'accounts' => [
  1839. AccountService::getMastodon($from)
  1840. ],
  1841. 'last_status' => StatusService::getDirectMessage($dm->status_id)
  1842. ];
  1843. return $res;
  1844. })
  1845. ->filter(function($dm) {
  1846. return isset($dm['accounts']) && count($dm['accounts']);
  1847. })
  1848. ->unique(function($item, $key) {
  1849. return $item['accounts'][0]['id'];
  1850. })
  1851. ->values();
  1852. return $this->json($dms);
  1853. }
  1854. /**
  1855. * GET /api/v1/statuses/{id}
  1856. *
  1857. * @param integer $id
  1858. *
  1859. * @return StatusTransformer
  1860. */
  1861. public function statusById(Request $request, $id)
  1862. {
  1863. abort_if(!$request->user(), 403);
  1864. $user = $request->user();
  1865. $res = StatusService::getMastodon($id, false);
  1866. if(!$res || !isset($res['visibility'])) {
  1867. abort(404);
  1868. }
  1869. $scope = $res['visibility'];
  1870. if(!in_array($scope, ['public', 'unlisted'])) {
  1871. if($scope === 'private') {
  1872. if($res['account']['id'] != $user->profile_id) {
  1873. abort_unless(FollowerService::follows($user->profile_id, $res['account']['id']), 403);
  1874. }
  1875. } else {
  1876. abort(400, 'Invalid request');
  1877. }
  1878. }
  1879. $res['favourited'] = LikeService::liked($user->profile_id, $res['id']);
  1880. $res['reblogged'] = ReblogService::get($user->profile_id, $res['id']);
  1881. return $this->json($res);
  1882. }
  1883. /**
  1884. * GET /api/v1/statuses/{id}/context
  1885. *
  1886. * @param integer $id
  1887. *
  1888. * @return StatusTransformer
  1889. */
  1890. public function statusContext(Request $request, $id)
  1891. {
  1892. abort_if(!$request->user(), 403);
  1893. $user = $request->user();
  1894. $pid = $user->profile_id;
  1895. $status = StatusService::getMastodon($id, false);
  1896. if(!$status || !isset($status['account'])) {
  1897. return response('', 404);
  1898. }
  1899. if($status['account']['id'] != $user->profile_id) {
  1900. if($status['visibility'] == 'private') {
  1901. if(!FollowerService::follows($user->profile_id, $status['account']['id'])) {
  1902. return response('', 404);
  1903. }
  1904. } else {
  1905. if(!in_array($status['visibility'], ['public','unlisted'])) {
  1906. return response('', 404);
  1907. }
  1908. }
  1909. }
  1910. $ancestors = [];
  1911. $descendants = [];
  1912. if($status['in_reply_to_id']) {
  1913. $ancestors[] = StatusService::getMastodon($status['in_reply_to_id'], false);
  1914. }
  1915. if($status['replies_count']) {
  1916. $descendants = DB::table('statuses')
  1917. ->where('in_reply_to_id', $id)
  1918. ->limit(20)
  1919. ->pluck('id')
  1920. ->map(function($sid) {
  1921. return StatusService::getMastodon($sid, false);
  1922. })
  1923. ->filter(function($post) {
  1924. return $post && isset($post['account']);
  1925. })
  1926. ->map(function($status) use($pid) {
  1927. $status['favourited'] = LikeService::liked($pid, $status['id']);
  1928. $status['reblogged'] = ReblogService::get($pid, $status['id']);
  1929. return $status;
  1930. })
  1931. ->values();
  1932. }
  1933. $res = [
  1934. 'ancestors' => $ancestors,
  1935. 'descendants' => $descendants
  1936. ];
  1937. return $this->json($res);
  1938. }
  1939. /**
  1940. * GET /api/v1/statuses/{id}/card
  1941. *
  1942. * @param integer $id
  1943. *
  1944. * @return StatusTransformer
  1945. */
  1946. public function statusCard(Request $request, $id)
  1947. {
  1948. abort_if(!$request->user(), 403);
  1949. $res = [];
  1950. return response()->json($res);
  1951. }
  1952. /**
  1953. * GET /api/v1/statuses/{id}/reblogged_by
  1954. *
  1955. * @param integer $id
  1956. *
  1957. * @return AccountTransformer
  1958. */
  1959. public function statusRebloggedBy(Request $request, $id)
  1960. {
  1961. abort_if(!$request->user(), 403);
  1962. $this->validate($request, [
  1963. 'page' => 'nullable|integer|min:1|max:40',
  1964. 'limit' => 'nullable|integer|min:1|max:100'
  1965. ]);
  1966. $limit = $request->input('limit') ?? 40;
  1967. $user = $request->user();
  1968. $status = Status::findOrFail($id);
  1969. if($status->profile_id !== $user->profile_id) {
  1970. if($status->scope == 'private') {
  1971. abort_if(!FollowerService::follows($user->profile_id, $status->profile_id), 403);
  1972. } else {
  1973. abort_if(!in_array($status->scope, ['public','unlisted']), 403);
  1974. }
  1975. }
  1976. $page = $request->input('page', 1);
  1977. $start = $page == 1 ? 0 : (($page * $limit) - $limit);
  1978. $end = $start + $limit - 1;
  1979. $ids = ReblogService::getPostReblogs($id, $start, $end);
  1980. if(empty($ids)) {
  1981. return [];
  1982. }
  1983. $res = collect($ids)
  1984. ->map(function($id) {
  1985. $status = StatusService::get($id);
  1986. if($status) {
  1987. return AccountService::get($status['account']['id']);
  1988. }
  1989. return;
  1990. })
  1991. ->filter(function($account) {
  1992. return $account && isset($account['id']);
  1993. })
  1994. ->values();
  1995. $url = $request->url();
  1996. $page = $request->input('page', 1);
  1997. $next = $page < 40 ? $page + 1 : 40;
  1998. $prev = $page > 1 ? $page - 1 : 1;
  1999. $links = '<'.$url.'?page='.$next.'&limit='.$limit.'>; rel="next", <'.$url.'?page='.$prev.'&limit='.$limit.'>; rel="prev"';
  2000. return $this->json($res, 200, ['Link' => $links]);
  2001. }
  2002. /**
  2003. * GET /api/v1/statuses/{id}/favourited_by
  2004. *
  2005. * @param integer $id
  2006. *
  2007. * @return AccountTransformer
  2008. */
  2009. public function statusFavouritedBy(Request $request, $id)
  2010. {
  2011. abort_if(!$request->user(), 403);
  2012. $this->validate($request, [
  2013. 'page' => 'nullable|integer|min:1|max:40',
  2014. 'limit' => 'nullable|integer|min:1|max:100'
  2015. ]);
  2016. $page = $request->input('page', 1);
  2017. $limit = $request->input('limit') ?? 40;
  2018. $user = $request->user();
  2019. $status = Status::findOrFail($id);
  2020. $offset = $page == 1 ? 0 : ($page * $limit - $limit);
  2021. if($offset > 100) {
  2022. if($user->profile_id != $status->profile_id) {
  2023. return [];
  2024. }
  2025. }
  2026. if($status->profile_id !== $user->profile_id) {
  2027. if($status->scope == 'private') {
  2028. abort_if(!$status->profile->followedBy($user->profile), 403);
  2029. } else {
  2030. abort_if(!in_array($status->scope, ['public','unlisted']), 403);
  2031. }
  2032. }
  2033. $res = DB::table('likes')
  2034. ->select('likes.id', 'likes.profile_id', 'likes.status_id', 'followers.created_at')
  2035. ->leftJoin('followers', function($join) use($user, $status) {
  2036. return $join->on('likes.profile_id', '=', 'followers.following_id')
  2037. ->where('followers.profile_id', $user->profile_id)
  2038. ->where('likes.status_id', $status->id);
  2039. })
  2040. ->whereStatusId($status->id)
  2041. ->orderByDesc('followers.created_at')
  2042. ->offset($offset)
  2043. ->limit($limit)
  2044. ->get()
  2045. ->map(function($like) {
  2046. $account = AccountService::getMastodon($like->profile_id);
  2047. $account['follows'] = isset($like->created_at);
  2048. return $account;
  2049. })
  2050. ->filter(function($account) use($user) {
  2051. return $account && isset($account['id']) && $account['id'] != $user->profile_id;
  2052. })
  2053. ->values();
  2054. $url = $request->url();
  2055. $page = $request->input('page', 1);
  2056. $next = $page < 40 ? $page + 1 : 40;
  2057. $prev = $page > 1 ? $page - 1 : 1;
  2058. $links = '<'.$url.'?page='.$next.'&limit='.$limit.'>; rel="next", <'.$url.'?page='.$prev.'&limit='.$limit.'>; rel="prev"';
  2059. return $this->json($res, 200, ['Link' => $links]);
  2060. }
  2061. /**
  2062. * POST /api/v1/statuses
  2063. *
  2064. *
  2065. * @return StatusTransformer
  2066. */
  2067. public function statusCreate(Request $request)
  2068. {
  2069. abort_if(!$request->user(), 403);
  2070. $this->validate($request, [
  2071. 'status' => 'nullable|string',
  2072. 'in_reply_to_id' => 'nullable',
  2073. 'media_ids' => 'sometimes|array|max:' . config_cache('pixelfed.max_album_length'),
  2074. 'sensitive' => 'nullable',
  2075. 'visibility' => 'string|in:private,unlisted,public',
  2076. 'spoiler_text' => 'sometimes|string|max:140',
  2077. ]);
  2078. if(config('costar.enabled') == true) {
  2079. $blockedKeywords = config('costar.keyword.block');
  2080. if($blockedKeywords !== null && $request->status) {
  2081. $keywords = config('costar.keyword.block');
  2082. foreach($keywords as $kw) {
  2083. if(Str::contains($request->status, $kw) == true) {
  2084. abort(400, 'Invalid object. Contains banned keyword.');
  2085. }
  2086. }
  2087. }
  2088. }
  2089. if(!$request->filled('media_ids') && !$request->filled('in_reply_to_id')) {
  2090. abort(403, 'Empty statuses are not allowed');
  2091. }
  2092. $ids = $request->input('media_ids');
  2093. $in_reply_to_id = $request->input('in_reply_to_id');
  2094. $user = $request->user();
  2095. $profile = $user->profile;
  2096. $limitKey = 'compose:rate-limit:store:' . $user->id;
  2097. $limitTtl = now()->addMinutes(15);
  2098. $limitReached = Cache::remember($limitKey, $limitTtl, function() use($user) {
  2099. $dailyLimit = Status::whereProfileId($user->profile_id)
  2100. ->whereNull('in_reply_to_id')
  2101. ->whereNull('reblog_of_id')
  2102. ->where('created_at', '>', now()->subDays(1))
  2103. ->count();
  2104. return $dailyLimit >= 100;
  2105. });
  2106. abort_if($limitReached == true, 429);
  2107. $visibility = $profile->is_private ? 'private' : (
  2108. $profile->unlisted == true &&
  2109. $request->input('visibility', 'public') == 'public' ?
  2110. 'unlisted' :
  2111. $request->input('visibility', 'public'));
  2112. if($user->last_active_at == null) {
  2113. return [];
  2114. }
  2115. $content = strip_tags($request->input('status'));
  2116. $rendered = Autolink::create()->autolink($content);
  2117. $cw = $user->profile->cw == true ? true : $request->input('sensitive', false);
  2118. $spoilerText = $cw && $request->filled('spoiler_text') ? $request->input('spoiler_text') : null;
  2119. if($in_reply_to_id) {
  2120. $parent = Status::findOrFail($in_reply_to_id);
  2121. $status = new Status;
  2122. $status->caption = $content;
  2123. $status->rendered = $rendered;
  2124. $status->scope = $visibility;
  2125. $status->visibility = $visibility;
  2126. $status->profile_id = $user->profile_id;
  2127. $status->is_nsfw = $cw;
  2128. $status->cw_summary = $spoilerText;
  2129. $status->in_reply_to_id = $parent->id;
  2130. $status->in_reply_to_profile_id = $parent->profile_id;
  2131. $status->save();
  2132. StatusService::del($parent->id);
  2133. Cache::forget('status:replies:all:' . $parent->id);
  2134. }
  2135. if($ids) {
  2136. if(Media::whereUserId($user->id)
  2137. ->whereNull('status_id')
  2138. ->find($ids)
  2139. ->count() == 0
  2140. ) {
  2141. abort(400, 'Invalid media_ids');
  2142. }
  2143. if(!$in_reply_to_id) {
  2144. $status = new Status;
  2145. $status->caption = $content;
  2146. $status->rendered = $rendered;
  2147. $status->profile_id = $user->profile_id;
  2148. $status->scope = 'draft';
  2149. $status->is_nsfw = $cw;
  2150. $status->cw_summary = $spoilerText;
  2151. $status->save();
  2152. }
  2153. $mimes = [];
  2154. foreach($ids as $k => $v) {
  2155. if($k + 1 > config_cache('pixelfed.max_album_length')) {
  2156. continue;
  2157. }
  2158. $m = Media::whereUserId($user->id)->whereNull('status_id')->findOrFail($v);
  2159. if($m->profile_id !== $user->profile_id || $m->status_id) {
  2160. abort(403, 'Invalid media id');
  2161. }
  2162. $m->status_id = $status->id;
  2163. $m->save();
  2164. array_push($mimes, $m->mime);
  2165. }
  2166. if(empty($mimes)) {
  2167. $status->delete();
  2168. abort(400, 'Invalid media ids');
  2169. }
  2170. $status->scope = $visibility;
  2171. $status->visibility = $visibility;
  2172. $status->type = StatusController::mimeTypeCheck($mimes);
  2173. $status->save();
  2174. }
  2175. if(!$status) {
  2176. abort(500, 'An error occured.');
  2177. }
  2178. NewStatusPipeline::dispatch($status);
  2179. if($status->in_reply_to_id) {
  2180. CommentPipeline::dispatch($parent, $status);
  2181. }
  2182. Cache::forget('user:account:id:'.$user->id);
  2183. Cache::forget('_api:statuses:recent_9:'.$user->profile_id);
  2184. Cache::forget('profile:status_count:'.$user->profile_id);
  2185. Cache::forget($user->storageUsedKey());
  2186. Cache::forget('profile:embed:' . $status->profile_id);
  2187. Cache::forget($limitKey);
  2188. $res = StatusService::getMastodon($status->id, false);
  2189. $res['favourited'] = false;
  2190. $res['language'] = 'en';
  2191. $res['bookmarked'] = false;
  2192. $res['card'] = null;
  2193. return $this->json($res);
  2194. }
  2195. /**
  2196. * DELETE /api/v1/statuses
  2197. *
  2198. * @param integer $id
  2199. *
  2200. * @return null
  2201. */
  2202. public function statusDelete(Request $request, $id)
  2203. {
  2204. abort_if(!$request->user(), 403);
  2205. $status = Status::whereProfileId($request->user()->profile->id)
  2206. ->findOrFail($id);
  2207. $resource = new Fractal\Resource\Item($status, new StatusTransformer());
  2208. Cache::forget('profile:status_count:'.$status->profile_id);
  2209. StatusDelete::dispatch($status);
  2210. $res = $this->fractal->createData($resource)->toArray();
  2211. $res['text'] = $res['content'];
  2212. unset($res['content']);
  2213. return $this->json($res);
  2214. }
  2215. /**
  2216. * POST /api/v1/statuses/{id}/reblog
  2217. *
  2218. * @param integer $id
  2219. *
  2220. * @return StatusTransformer
  2221. */
  2222. public function statusShare(Request $request, $id)
  2223. {
  2224. abort_if(!$request->user(), 403);
  2225. $user = $request->user();
  2226. $status = Status::whereScope('public')->findOrFail($id);
  2227. if($status->profile_id !== $user->profile_id) {
  2228. if($status->scope == 'private') {
  2229. abort_if(!FollowerService::follows($user->profile_id, $status->profile_id), 403);
  2230. } else {
  2231. abort_if(!in_array($status->scope, ['public','unlisted']), 403);
  2232. }
  2233. }
  2234. $share = Status::firstOrCreate([
  2235. 'profile_id' => $user->profile_id,
  2236. 'reblog_of_id' => $status->id,
  2237. 'type' => 'share',
  2238. 'in_reply_to_profile_id' => $status->profile_id,
  2239. 'scope' => 'public',
  2240. 'visibility' => 'public'
  2241. ]);
  2242. if($share->wasRecentlyCreated == true) {
  2243. SharePipeline::dispatch($share);
  2244. }
  2245. StatusService::del($status->id);
  2246. ReblogService::add($user->profile_id, $status->id);
  2247. $res = StatusService::getMastodon($status->id);
  2248. $res['reblogged'] = true;
  2249. return $this->json($res);
  2250. }
  2251. /**
  2252. * POST /api/v1/statuses/{id}/unreblog
  2253. *
  2254. * @param integer $id
  2255. *
  2256. * @return StatusTransformer
  2257. */
  2258. public function statusUnshare(Request $request, $id)
  2259. {
  2260. abort_if(!$request->user(), 403);
  2261. $user = $request->user();
  2262. $status = Status::whereScope('public')->findOrFail($id);
  2263. if($status->profile_id !== $user->profile_id) {
  2264. if($status->scope == 'private') {
  2265. abort_if(!FollowerService::follows($user->profile_id, $status->profile_id), 403);
  2266. } else {
  2267. abort_if(!in_array($status->scope, ['public','unlisted']), 403);
  2268. }
  2269. }
  2270. $reblog = Status::whereProfileId($user->profile_id)
  2271. ->whereReblogOfId($status->id)
  2272. ->first();
  2273. if(!$reblog) {
  2274. $res = StatusService::getMastodon($status->id);
  2275. $res['reblogged'] = false;
  2276. return $this->json($res);
  2277. }
  2278. UndoSharePipeline::dispatch($reblog);
  2279. ReblogService::del($user->profile_id, $status->id);
  2280. $res = StatusService::getMastodon($status->id);
  2281. $res['reblogged'] = false;
  2282. return $this->json($res);
  2283. }
  2284. /**
  2285. * GET /api/v1/timelines/tag/{hashtag}
  2286. *
  2287. * @param string $hashtag
  2288. *
  2289. * @return StatusTransformer
  2290. */
  2291. public function timelineHashtag(Request $request, $hashtag)
  2292. {
  2293. $this->validate($request,[
  2294. 'page' => 'nullable|integer|max:40',
  2295. 'min_id' => 'nullable|integer|min:0|max:' . PHP_INT_MAX,
  2296. 'max_id' => 'nullable|integer|min:0|max:' . PHP_INT_MAX,
  2297. 'limit' => 'nullable|integer|max:100'
  2298. ]);
  2299. $tag = Hashtag::whereName($hashtag)
  2300. ->orWhere('slug', $hashtag)
  2301. ->first();
  2302. if(!$tag) {
  2303. return response()->json([]);
  2304. }
  2305. $min = $request->input('min_id');
  2306. $max = $request->input('max_id');
  2307. $limit = $request->input('limit', 20);
  2308. if(!$min && !$max) {
  2309. $id = 1;
  2310. $dir = '>';
  2311. } else {
  2312. $dir = $min ? '>' : '<';
  2313. $id = $min ?? $max;
  2314. }
  2315. $res = StatusHashtag::whereHashtagId($tag->id)
  2316. ->whereStatusVisibility('public')
  2317. ->where('status_id', $dir, $id)
  2318. ->latest()
  2319. ->limit($limit)
  2320. ->pluck('status_id')
  2321. ->map(function ($i) {
  2322. if($i) {
  2323. return StatusService::getMastodon($i);
  2324. }
  2325. })
  2326. ->filter(function($i) {
  2327. return $i && isset($i['account']);
  2328. })
  2329. ->values()
  2330. ->toArray();
  2331. return $this->json($res);
  2332. }
  2333. /**
  2334. * GET /api/v1/bookmarks
  2335. *
  2336. *
  2337. *
  2338. * @return StatusTransformer
  2339. */
  2340. public function bookmarks(Request $request)
  2341. {
  2342. abort_if(!$request->user(), 403);
  2343. $this->validate($request, [
  2344. 'limit' => 'nullable|integer|min:1|max:40',
  2345. 'max_id' => 'nullable|integer|min:0',
  2346. 'since_id' => 'nullable|integer|min:0',
  2347. 'min_id' => 'nullable|integer|min:0'
  2348. ]);
  2349. $pid = $request->user()->profile_id;
  2350. $limit = $request->input('limit') ?? 20;
  2351. $max_id = $request->input('max_id');
  2352. $since_id = $request->input('since_id');
  2353. $min_id = $request->input('min_id');
  2354. $dir = $min_id ? '>' : '<';
  2355. $id = $min_id ?? $max_id;
  2356. if($id) {
  2357. $bookmarks = Bookmark::whereProfileId($pid)
  2358. ->where('status_id', $dir, $id)
  2359. ->limit($limit)
  2360. ->pluck('status_id');
  2361. } else {
  2362. $bookmarks = Bookmark::whereProfileId($pid)
  2363. ->latest()
  2364. ->limit($limit)
  2365. ->pluck('status_id');
  2366. }
  2367. $res = [];
  2368. foreach($bookmarks as $id) {
  2369. $res[] = \App\Services\StatusService::getMastodon($id);
  2370. }
  2371. return $this->json($res);
  2372. }
  2373. /**
  2374. * POST /api/v1/statuses/{id}/bookmark
  2375. *
  2376. *
  2377. *
  2378. * @return StatusTransformer
  2379. */
  2380. public function bookmarkStatus(Request $request, $id)
  2381. {
  2382. abort_if(!$request->user(), 403);
  2383. $status = Status::whereNull('uri')
  2384. ->whereScope('public')
  2385. ->findOrFail($id);
  2386. Bookmark::firstOrCreate([
  2387. 'status_id' => $status->id,
  2388. 'profile_id' => $request->user()->profile_id
  2389. ]);
  2390. $res = StatusService::getMastodon($status->id);
  2391. return $this->json($res);
  2392. }
  2393. /**
  2394. * POST /api/v1/statuses/{id}/unbookmark
  2395. *
  2396. *
  2397. *
  2398. * @return StatusTransformer
  2399. */
  2400. public function unbookmarkStatus(Request $request, $id)
  2401. {
  2402. abort_if(!$request->user(), 403);
  2403. $status = Status::whereNull('uri')
  2404. ->whereScope('public')
  2405. ->findOrFail($id);
  2406. $bookmark = Bookmark::whereStatusId($status->id)
  2407. ->whereProfileId($request->user()->profile_id)
  2408. ->firstOrFail();
  2409. $bookmark->delete();
  2410. $res = StatusService::getMastodon($status->id);
  2411. return $this->json($res);
  2412. }
  2413. /**
  2414. * GET /api/v2/search
  2415. *
  2416. *
  2417. * @return array
  2418. */
  2419. public function searchV2(Request $request)
  2420. {
  2421. abort_if(!$request->user(), 403);
  2422. $this->validate($request, [
  2423. 'q' => 'required|string|min:1|max:100',
  2424. 'account_id' => 'nullable|string',
  2425. 'max_id' => 'nullable|string',
  2426. 'min_id' => 'nullable|string',
  2427. 'type' => 'nullable|in:accounts,hashtags,statuses',
  2428. 'exclude_unreviewed' => 'nullable',
  2429. 'resolve' => 'nullable',
  2430. 'limit' => 'nullable|integer|max:40',
  2431. 'offset' => 'nullable|integer',
  2432. 'following' => 'nullable'
  2433. ]);
  2434. return $this->json(SearchApiV2Service::query($request, true));
  2435. }
  2436. /**
  2437. * GET /api/v1/discover/posts
  2438. *
  2439. *
  2440. * @return array
  2441. */
  2442. public function discoverPosts(Request $request)
  2443. {
  2444. abort_if(!$request->user(), 403);
  2445. $this->validate($request, [
  2446. 'limit' => 'integer|min:1|max:40'
  2447. ]);
  2448. $limit = $request->input('limit', 40);
  2449. $pid = $request->user()->profile_id;
  2450. $filters = UserFilterService::filters($pid);
  2451. $forYou = DiscoverService::getForYou();
  2452. $posts = $forYou->take(50)->map(function($post) {
  2453. return StatusService::getMastodon($post);
  2454. })
  2455. ->filter(function($post) use($filters) {
  2456. return $post &&
  2457. isset($post['account']) &&
  2458. isset($post['account']['id']) &&
  2459. !in_array($post['account']['id'], $filters);
  2460. })
  2461. ->take(12)
  2462. ->values();
  2463. return $this->json(compact('posts'));
  2464. }
  2465. /**
  2466. * GET /api/v2/statuses/{id}/replies
  2467. *
  2468. *
  2469. * @return array
  2470. */
  2471. public function statusReplies(Request $request, $id)
  2472. {
  2473. abort_if(!$request->user(), 403);
  2474. $this->validate($request, [
  2475. 'limit' => 'int|min:1|max:10',
  2476. 'sort' => 'in:all,newest,popular'
  2477. ]);
  2478. $limit = $request->input('limit', 3);
  2479. $pid = $request->user()->profile_id;
  2480. $status = StatusService::getMastodon($id, false);
  2481. abort_if(!$status, 404);
  2482. if($status['visibility'] == 'private') {
  2483. if($pid != $status['account']['id']) {
  2484. abort_unless(FollowerService::follows($pid, $status['account']['id']), 404);
  2485. }
  2486. }
  2487. $sortBy = $request->input('sort', 'all');
  2488. if($sortBy == 'all' && isset($status['replies_count']) && $status['replies_count'] && $request->has('refresh_cache')) {
  2489. if(!Cache::has('status:replies:all-rc:' . $id)) {
  2490. Cache::forget('status:replies:all:' . $id);
  2491. Cache::put('status:replies:all-rc:' . $id, true, 300);
  2492. }
  2493. }
  2494. if($sortBy == 'all' && !$request->has('cursor')) {
  2495. $ids = Cache::remember('status:replies:all:' . $id, 86400, function() use($id) {
  2496. return DB::table('statuses')
  2497. ->where('in_reply_to_id', $id)
  2498. ->orderBy('id')
  2499. ->cursorPaginate(3);
  2500. });
  2501. } else {
  2502. $ids = DB::table('statuses')
  2503. ->where('in_reply_to_id', $id)
  2504. ->when($sortBy, function($q, $sortBy) {
  2505. if($sortBy === 'all') {
  2506. return $q->orderBy('id');
  2507. }
  2508. if($sortBy === 'newest') {
  2509. return $q->orderByDesc('created_at');
  2510. }
  2511. if($sortBy === 'popular') {
  2512. return $q->orderByDesc('likes_count');
  2513. }
  2514. })
  2515. ->cursorPaginate($limit);
  2516. }
  2517. $data = $ids->map(function($post) use($pid) {
  2518. $status = StatusService::get($post->id, false);
  2519. if(!$status || !isset($status['id'])) {
  2520. return false;
  2521. }
  2522. $status['favourited'] = LikeService::liked($pid, $post->id);
  2523. return $status;
  2524. })
  2525. ->filter(function($post) {
  2526. return $post && isset($post['id']) && isset($post['account']);
  2527. })
  2528. ->values();
  2529. $res = [
  2530. 'data' => $data,
  2531. 'next' => $ids->nextPageUrl()
  2532. ];
  2533. return $this->json($res);
  2534. }
  2535. /**
  2536. * GET /api/v2/statuses/{id}/state
  2537. *
  2538. *
  2539. * @return array
  2540. */
  2541. public function statusState(Request $request, $id)
  2542. {
  2543. abort_if(!$request->user(), 403);
  2544. $status = Status::findOrFail($id);
  2545. $pid = $request->user()->profile_id;
  2546. abort_if(!in_array($status->scope, ['public', 'unlisted', 'private']), 404);
  2547. return $this->json(StatusService::getState($status->id, $pid));
  2548. }
  2549. /**
  2550. * GET /api/v1/discover/accounts/popular
  2551. *
  2552. *
  2553. * @return array
  2554. */
  2555. public function discoverAccountsPopular(Request $request)
  2556. {
  2557. abort_if(!$request->user(), 403);
  2558. $pid = $request->user()->profile_id;
  2559. $ids = DB::table('profiles')
  2560. ->where('is_private', false)
  2561. ->whereNull('status')
  2562. ->orderByDesc('profiles.followers_count')
  2563. ->limit(20)
  2564. ->get();
  2565. $ids = $ids->map(function($profile) {
  2566. return AccountService::getMastodon($profile->id);
  2567. })
  2568. ->filter(function($profile) use($pid) {
  2569. return $profile &&
  2570. isset($profile['id']) &&
  2571. !FollowerService::follows($pid, $profile['id']) &&
  2572. $profile['id'] != $pid;
  2573. })
  2574. ->take(6)
  2575. ->values();
  2576. return $this->json($ids);
  2577. }
  2578. /**
  2579. * GET /api/v1/preferences
  2580. *
  2581. *
  2582. * @return array
  2583. */
  2584. public function getPreferences(Request $request)
  2585. {
  2586. abort_if(!$request->user(), 403);
  2587. $pid = $request->user()->profile_id;
  2588. $account = AccountService::get($pid);
  2589. return $this->json([
  2590. 'posting:default:visibility' => $account['locked'] ? 'private' : 'public',
  2591. 'posting:default:sensitive' => false,
  2592. 'posting:default:language' => null,
  2593. 'reading:expand:media' => 'default',
  2594. 'reading:expand:spoilers' => false
  2595. ]);
  2596. }
  2597. /**
  2598. * GET /api/v1/trends
  2599. *
  2600. *
  2601. * @return array
  2602. */
  2603. public function getTrends(Request $request)
  2604. {
  2605. abort_if(!$request->user(), 403);
  2606. return $this->json([]);
  2607. }
  2608. /**
  2609. * GET /api/v1/announcements
  2610. *
  2611. *
  2612. * @return array
  2613. */
  2614. public function getAnnouncements(Request $request)
  2615. {
  2616. abort_if(!$request->user(), 403);
  2617. return $this->json([]);
  2618. }
  2619. /**
  2620. * GET /api/v1/markers
  2621. *
  2622. *
  2623. * @return array
  2624. */
  2625. public function getMarkers(Request $request)
  2626. {
  2627. abort_if(!$request->user(), 403);
  2628. $type = $request->input('timeline');
  2629. if(is_array($type)) {
  2630. $type = $type[0];
  2631. }
  2632. if(!$type || !in_array($type, ['home', 'notifications'])) {
  2633. return $this->json([]);
  2634. }
  2635. $pid = $request->user()->profile_id;
  2636. return $this->json(MarkerService::get($pid, $type));
  2637. }
  2638. /**
  2639. * POST /api/v1/markers
  2640. *
  2641. *
  2642. * @return array
  2643. */
  2644. public function setMarkers(Request $request)
  2645. {
  2646. abort_if(!$request->user(), 403);
  2647. $pid = $request->user()->profile_id;
  2648. $home = $request->input('home.last_read_id');
  2649. $notifications = $request->input('notifications.last_read_id');
  2650. if($home) {
  2651. return $this->json(MarkerService::set($pid, 'home', $home));
  2652. }
  2653. if($notifications) {
  2654. return $this->json(MarkerService::set($pid, 'notifications', $notifications));
  2655. }
  2656. return $this->json([]);
  2657. }
  2658. }