ApiV1Controller.php 70 KB

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