ApiV1Controller.php 105 KB

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