ApiV1Controller.php 68 KB

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