ApiV1Controller.php 81 KB

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