ApiV1Controller.php 83 KB

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