ApiV1Controller.php 67 KB

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