ApiV1Controller.php 80 KB

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