ApiV1Controller.php 100 KB

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