ApiV1Controller.php 101 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786
  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. $followed = Follower::whereProfileId($profile->id)->whereFollowingId($pid)->first();
  951. if($followed) {
  952. $followed->delete();
  953. $profile->following_count = Follower::whereProfileId($profile->id)->count();
  954. $profile->save();
  955. $selfProfile = $user->profile;
  956. $selfProfile->followers_count = Follower::whereFollowingId($pid)->count();
  957. $selfProfile->save();
  958. FollowerService::remove($profile->id, $pid);
  959. AccountService::del($pid);
  960. AccountService::del($profile->id);
  961. }
  962. $following = Follower::whereProfileId($pid)->whereFollowingId($profile->id)->first();
  963. if($following) {
  964. $following->delete();
  965. $profile->followers_count = Follower::whereFollowingId($profile->id)->count();
  966. $profile->save();
  967. $selfProfile = $user->profile;
  968. $selfProfile->following_count = Follower::whereProfileId($pid)->count();
  969. $selfProfile->save();
  970. FollowerService::remove($pid, $profile->pid);
  971. AccountService::del($pid);
  972. AccountService::del($profile->id);
  973. }
  974. Notification::whereProfileId($pid)
  975. ->whereActorId($profile->id)
  976. ->get()
  977. ->map(function($n) use($pid) {
  978. NotificationService::del($pid, $n['id']);
  979. $n->forceDelete();
  980. });
  981. $filter = UserFilter::firstOrCreate([
  982. 'user_id' => $pid,
  983. 'filterable_id' => $profile->id,
  984. 'filterable_type' => 'App\Profile',
  985. 'filter_type' => 'block',
  986. ]);
  987. UserFilterService::block($pid, $id);
  988. RelationshipService::refresh($pid, $id);
  989. $resource = new Fractal\Resource\Item($profile, new RelationshipTransformer());
  990. $res = $this->fractal->createData($resource)->toArray();
  991. return $this->json($res);
  992. }
  993. /**
  994. * POST /api/v1/accounts/{id}/unblock
  995. *
  996. * @param integer $id
  997. *
  998. * @return \App\Transformer\Api\RelationshipTransformer
  999. */
  1000. public function accountUnblockById(Request $request, $id)
  1001. {
  1002. abort_if(!$request->user(), 403);
  1003. if(config('pixelfed.bouncer.cloud_ips.ban_api')) {
  1004. abort_if(BouncerService::checkIp($request->ip()), 404);
  1005. }
  1006. $user = $request->user();
  1007. $pid = $user->profile_id ?? $user->profile->id;
  1008. if(intval($id) === intval($pid)) {
  1009. abort(400, 'You cannot unblock yourself');
  1010. }
  1011. $profile = Profile::findOrFail($id);
  1012. $filter = UserFilter::whereUserId($pid)
  1013. ->whereFilterableId($profile->id)
  1014. ->whereFilterableType('App\Profile')
  1015. ->whereFilterType('block')
  1016. ->first();
  1017. if($filter) {
  1018. $filter->delete();
  1019. UserFilterService::unblock($pid, $profile->id);
  1020. RelationshipService::refresh($pid, $id);
  1021. }
  1022. $resource = new Fractal\Resource\Item($profile, new RelationshipTransformer());
  1023. $res = $this->fractal->createData($resource)->toArray();
  1024. return $this->json($res);
  1025. }
  1026. /**
  1027. * GET /api/v1/custom_emojis
  1028. *
  1029. * Return custom emoji
  1030. *
  1031. * @return array
  1032. */
  1033. public function customEmojis()
  1034. {
  1035. return response(CustomEmojiService::all())->header('Content-Type', 'application/json');
  1036. }
  1037. /**
  1038. * GET /api/v1/domain_blocks
  1039. *
  1040. * Return empty array
  1041. *
  1042. * @return array
  1043. */
  1044. public function accountDomainBlocks(Request $request)
  1045. {
  1046. abort_if(!$request->user(), 403);
  1047. return response()->json([]);
  1048. }
  1049. /**
  1050. * GET /api/v1/endorsements
  1051. *
  1052. * Return empty array
  1053. *
  1054. * @return array
  1055. */
  1056. public function accountEndorsements(Request $request)
  1057. {
  1058. abort_if(!$request->user(), 403);
  1059. return response()->json([]);
  1060. }
  1061. /**
  1062. * GET /api/v1/favourites
  1063. *
  1064. * Returns collection of liked statuses
  1065. *
  1066. * @return \App\Transformer\Api\StatusTransformer
  1067. */
  1068. public function accountFavourites(Request $request)
  1069. {
  1070. abort_if(!$request->user(), 403);
  1071. $this->validate($request, [
  1072. 'limit' => 'sometimes|integer|min:1|max:20'
  1073. ]);
  1074. if(config('pixelfed.bouncer.cloud_ips.ban_api')) {
  1075. abort_if(BouncerService::checkIp($request->ip()), 404);
  1076. }
  1077. $user = $request->user();
  1078. $maxId = $request->input('max_id');
  1079. $minId = $request->input('min_id');
  1080. $limit = $request->input('limit') ?? 10;
  1081. $res = Like::whereProfileId($user->profile_id)
  1082. ->when($maxId, function($q, $maxId) {
  1083. return $q->where('id', '<', $maxId);
  1084. })
  1085. ->when($minId, function($q, $minId) {
  1086. return $q->where('id', '>', $minId);
  1087. })
  1088. ->orderByDesc('id')
  1089. ->limit($limit)
  1090. ->get()
  1091. ->map(function($like) {
  1092. $status = StatusService::getMastodon($like['status_id'], false);
  1093. $status['favourited'] = true;
  1094. $status['like_id'] = $like->id;
  1095. $status['liked_at'] = str_replace('+00:00', 'Z', $like->created_at->format(DATE_RFC3339_EXTENDED));
  1096. return $status;
  1097. })
  1098. ->filter(function($status) {
  1099. return $status && isset($status['id'], $status['like_id']);
  1100. })
  1101. ->values();
  1102. if($res->count()) {
  1103. $ids = $res->map(function($status) {
  1104. return $status['like_id'];
  1105. });
  1106. $max = $ids->max();
  1107. $min = $ids->min();
  1108. $baseUrl = config('app.url') . '/api/v1/favourites?limit=' . $limit . '&';
  1109. $link = '<'.$baseUrl.'max_id='.$max.'>; rel="next",<'.$baseUrl.'min_id='.$min.'>; rel="prev"';
  1110. return $this->json($res, 200, ['Link' => $link]);
  1111. } else {
  1112. return $this->json($res);
  1113. }
  1114. }
  1115. /**
  1116. * POST /api/v1/statuses/{id}/favourite
  1117. *
  1118. * @param integer $id
  1119. *
  1120. * @return \App\Transformer\Api\StatusTransformer
  1121. */
  1122. public function statusFavouriteById(Request $request, $id)
  1123. {
  1124. abort_if(!$request->user(), 403);
  1125. if(config('pixelfed.bouncer.cloud_ips.ban_api')) {
  1126. abort_if(BouncerService::checkIp($request->ip()), 404);
  1127. }
  1128. $user = $request->user();
  1129. $status = StatusService::getMastodon($id, false);
  1130. abort_unless($status, 400);
  1131. $spid = $status['account']['id'];
  1132. if(intval($spid) !== intval($user->profile_id)) {
  1133. if($status['visibility'] == 'private') {
  1134. abort_if(!FollowerService::follows($user->profile_id, $spid), 403);
  1135. } else {
  1136. abort_if(!in_array($status['visibility'], ['public','unlisted']), 403);
  1137. }
  1138. }
  1139. abort_if(
  1140. Like::whereProfileId($user->profile_id)
  1141. ->where('created_at', '>', now()->subDay())
  1142. ->count() >= Like::MAX_PER_DAY,
  1143. 429
  1144. );
  1145. $blocks = UserFilterService::blocks($spid);
  1146. if($blocks && in_array($user->profile_id, $blocks)) {
  1147. abort(422);
  1148. }
  1149. $like = Like::firstOrCreate([
  1150. 'profile_id' => $user->profile_id,
  1151. 'status_id' => $status['id']
  1152. ]);
  1153. if($like->wasRecentlyCreated == true) {
  1154. $like->status_profile_id = $spid;
  1155. $like->is_comment = !empty($status['in_reply_to_id']);
  1156. $like->save();
  1157. Status::findOrFail($status['id'])->update([
  1158. 'likes_count' => ($status['favourites_count'] ?? 0) + 1
  1159. ]);
  1160. LikePipeline::dispatch($like);
  1161. }
  1162. $status['favourited'] = true;
  1163. $status['favourites_count'] = $status['favourites_count'] + 1;
  1164. return $this->json($status);
  1165. }
  1166. /**
  1167. * POST /api/v1/statuses/{id}/unfavourite
  1168. *
  1169. * @param integer $id
  1170. *
  1171. * @return \App\Transformer\Api\StatusTransformer
  1172. */
  1173. public function statusUnfavouriteById(Request $request, $id)
  1174. {
  1175. abort_if(!$request->user(), 403);
  1176. if(config('pixelfed.bouncer.cloud_ips.ban_api')) {
  1177. abort_if(BouncerService::checkIp($request->ip()), 404);
  1178. }
  1179. $user = $request->user();
  1180. $status = Status::findOrFail($id);
  1181. if(intval($status->profile_id) !== intval($user->profile_id)) {
  1182. if($status->scope == 'private') {
  1183. abort_if(!$status->profile->followedBy($user->profile), 403);
  1184. } else {
  1185. abort_if(!in_array($status->scope, ['public','unlisted']), 403);
  1186. }
  1187. }
  1188. $like = Like::whereProfileId($user->profile_id)
  1189. ->whereStatusId($status->id)
  1190. ->first();
  1191. if($like) {
  1192. $like->forceDelete();
  1193. $status->likes_count = $status->likes()->count();
  1194. $status->save();
  1195. }
  1196. StatusService::del($status->id);
  1197. $res = StatusService::getMastodon($status->id, false);
  1198. $res['favourited'] = false;
  1199. return $this->json($res);
  1200. }
  1201. /**
  1202. * GET /api/v1/filters
  1203. *
  1204. * Return empty response since we filter server side
  1205. *
  1206. * @return array
  1207. */
  1208. public function accountFilters(Request $request)
  1209. {
  1210. abort_if(!$request->user(), 403);
  1211. return response()->json([]);
  1212. }
  1213. /**
  1214. * GET /api/v1/follow_requests
  1215. *
  1216. * Return array of Accounts that have sent follow requests
  1217. *
  1218. * @return \App\Transformer\Api\AccountTransformer
  1219. */
  1220. public function accountFollowRequests(Request $request)
  1221. {
  1222. abort_if(!$request->user(), 403);
  1223. $this->validate($request, [
  1224. 'limit' => 'sometimes|integer|min:1|max:100'
  1225. ]);
  1226. if(config('pixelfed.bouncer.cloud_ips.ban_api')) {
  1227. abort_if(BouncerService::checkIp($request->ip()), 404);
  1228. }
  1229. $user = $request->user();
  1230. $res = FollowRequest::whereFollowingId($user->profile->id)
  1231. ->limit($request->input('limit', 40))
  1232. ->pluck('follower_id')
  1233. ->map(function($id) {
  1234. return AccountService::getMastodon($id, true);
  1235. })
  1236. ->filter(function($acct) {
  1237. return $acct && isset($acct['id']);
  1238. })
  1239. ->values();
  1240. return $this->json($res);
  1241. }
  1242. /**
  1243. * POST /api/v1/follow_requests/{id}/authorize
  1244. *
  1245. * @param integer $id
  1246. *
  1247. * @return null
  1248. */
  1249. public function accountFollowRequestAccept(Request $request, $id)
  1250. {
  1251. abort_if(!$request->user(), 403);
  1252. $pid = $request->user()->profile_id;
  1253. $target = AccountService::getMastodon($id);
  1254. if(!$target) {
  1255. return response()->json(['error' => 'Record not found'], 404);
  1256. }
  1257. $followRequest = FollowRequest::whereFollowingId($pid)->whereFollowerId($id)->first();
  1258. if(!$followRequest) {
  1259. return response()->json(['error' => 'Record not found'], 404);
  1260. }
  1261. $follower = $followRequest->follower;
  1262. $follow = new Follower();
  1263. $follow->profile_id = $follower->id;
  1264. $follow->following_id = $pid;
  1265. $follow->save();
  1266. $profile = Profile::findOrFail($pid);
  1267. $profile->followers_count++;
  1268. $profile->save();
  1269. AccountService::del($profile->id);
  1270. $profile = Profile::findOrFail($follower->id);
  1271. $profile->following_count++;
  1272. $profile->save();
  1273. AccountService::del($profile->id);
  1274. if($follower->domain != null && $follower->private_key === null) {
  1275. FollowAcceptPipeline::dispatch($followRequest)->onQueue('follow');
  1276. } else {
  1277. FollowPipeline::dispatch($follow);
  1278. $followRequest->delete();
  1279. }
  1280. RelationshipService::refresh($pid, $id);
  1281. $res = RelationshipService::get($pid, $id);
  1282. $res['followed_by'] = true;
  1283. return $this->json($res);
  1284. }
  1285. /**
  1286. * POST /api/v1/follow_requests/{id}/reject
  1287. *
  1288. * @param integer $id
  1289. *
  1290. * @return null
  1291. */
  1292. public function accountFollowRequestReject(Request $request, $id)
  1293. {
  1294. abort_if(!$request->user(), 403);
  1295. $pid = $request->user()->profile_id;
  1296. $target = AccountService::getMastodon($id);
  1297. if(!$target) {
  1298. return response()->json(['error' => 'Record not found'], 404);
  1299. }
  1300. $followRequest = FollowRequest::whereFollowingId($pid)->whereFollowerId($id)->first();
  1301. if(!$followRequest) {
  1302. return response()->json(['error' => 'Record not found'], 404);
  1303. }
  1304. $follower = $followRequest->follower;
  1305. if($follower->domain != null && $follower->private_key === null) {
  1306. FollowRejectPipeline::dispatch($followRequest)->onQueue('follow');
  1307. } else {
  1308. $followRequest->delete();
  1309. }
  1310. RelationshipService::refresh($pid, $id);
  1311. $res = RelationshipService::get($pid, $id);
  1312. return $this->json($res);
  1313. }
  1314. /**
  1315. * GET /api/v1/suggestions
  1316. *
  1317. * Return empty array as we don't support suggestions
  1318. *
  1319. * @return null
  1320. */
  1321. public function accountSuggestions(Request $request)
  1322. {
  1323. abort_if(!$request->user(), 403);
  1324. // todo
  1325. return response()->json([]);
  1326. }
  1327. /**
  1328. * GET /api/v1/instance
  1329. *
  1330. * Information about the server.
  1331. *
  1332. * @return Instance
  1333. */
  1334. public function instance(Request $request)
  1335. {
  1336. $res = Cache::remember('api:v1:instance-data-response-v1', 1800, function () {
  1337. $contact = Cache::remember('api:v1:instance-data:contact', 604800, function () {
  1338. $admin = User::whereIsAdmin(true)->first();
  1339. return $admin && isset($admin->profile_id) ?
  1340. AccountService::getMastodon($admin->profile_id, true) :
  1341. null;
  1342. });
  1343. $stats = Cache::remember('api:v1:instance-data:stats', 43200, function () {
  1344. return [
  1345. 'user_count' => User::count(),
  1346. 'status_count' => Status::whereNull('uri')->count(),
  1347. 'domain_count' => Instance::count(),
  1348. ];
  1349. });
  1350. $rules = Cache::remember('api:v1:instance-data:rules', 604800, function () {
  1351. return config_cache('app.rules') ?
  1352. collect(json_decode(config_cache('app.rules'), true))
  1353. ->map(function($rule, $key) {
  1354. $id = $key + 1;
  1355. return [
  1356. 'id' => "{$id}",
  1357. 'text' => $rule
  1358. ];
  1359. })
  1360. ->toArray() : [];
  1361. });
  1362. return [
  1363. 'uri' => config('pixelfed.domain.app'),
  1364. 'title' => config('app.name'),
  1365. 'short_description' => config_cache('app.short_description'),
  1366. 'description' => config_cache('app.description'),
  1367. 'email' => config('instance.email'),
  1368. 'version' => '2.7.2 (compatible; Pixelfed ' . config('pixelfed.version') .')',
  1369. 'urls' => [
  1370. 'streaming_api' => 'wss://' . config('pixelfed.domain.app')
  1371. ],
  1372. 'stats' => $stats,
  1373. 'thumbnail' => config_cache('app.banner_image') ?? url(Storage::url('public/headers/default.jpg')),
  1374. 'languages' => [config('app.locale')],
  1375. 'registrations' => (bool) config_cache('pixelfed.open_registration'),
  1376. 'approval_required' => false,
  1377. 'contact_account' => $contact,
  1378. 'rules' => $rules,
  1379. 'configuration' => [
  1380. 'media_attachments' => [
  1381. 'image_matrix_limit' => 16777216,
  1382. 'image_size_limit' => config('pixelfed.max_photo_size') * 1024,
  1383. 'supported_mime_types' => explode(',', config('pixelfed.media_types')),
  1384. 'video_frame_rate_limit' => 120,
  1385. 'video_matrix_limit' => 2304000,
  1386. 'video_size_limit' => config('pixelfed.max_photo_size') * 1024,
  1387. ],
  1388. 'polls' => [
  1389. 'max_characters_per_option' => 50,
  1390. 'max_expiration' => 2629746,
  1391. 'max_options' => 4,
  1392. 'min_expiration' => 300
  1393. ],
  1394. 'statuses' => [
  1395. 'characters_reserved_per_url' => 23,
  1396. 'max_characters' => (int) config('pixelfed.max_caption_length'),
  1397. 'max_media_attachments' => (int) config('pixelfed.max_album_length')
  1398. ]
  1399. ]
  1400. ];
  1401. });
  1402. return $this->json($res);
  1403. }
  1404. /**
  1405. * GET /api/v1/lists
  1406. *
  1407. * Return empty array as we don't support lists
  1408. *
  1409. * @return null
  1410. */
  1411. public function accountLists(Request $request)
  1412. {
  1413. abort_if(!$request->user(), 403);
  1414. return response()->json([]);
  1415. }
  1416. /**
  1417. * GET /api/v1/accounts/{id}/lists
  1418. *
  1419. * @param integer $id
  1420. *
  1421. * @return null
  1422. */
  1423. public function accountListsById(Request $request, $id)
  1424. {
  1425. abort_if(!$request->user(), 403);
  1426. return response()->json([]);
  1427. }
  1428. /**
  1429. * POST /api/v1/media
  1430. *
  1431. *
  1432. * @return MediaTransformer
  1433. */
  1434. public function mediaUpload(Request $request)
  1435. {
  1436. abort_if(!$request->user(), 403);
  1437. if(config('pixelfed.bouncer.cloud_ips.ban_api')) {
  1438. abort_if(BouncerService::checkIp($request->ip()), 404);
  1439. }
  1440. $this->validate($request, [
  1441. 'file.*' => [
  1442. 'required_without:file',
  1443. 'mimetypes:' . config_cache('pixelfed.media_types'),
  1444. 'max:' . config_cache('pixelfed.max_photo_size'),
  1445. ],
  1446. 'file' => [
  1447. 'required_without:file.*',
  1448. 'mimetypes:' . config_cache('pixelfed.media_types'),
  1449. 'max:' . config_cache('pixelfed.max_photo_size'),
  1450. ],
  1451. 'filter_name' => 'nullable|string|max:24',
  1452. 'filter_class' => 'nullable|alpha_dash|max:24',
  1453. 'description' => 'nullable|string|max:' . config_cache('pixelfed.max_altext_length')
  1454. ]);
  1455. $user = $request->user();
  1456. if($user->last_active_at == null) {
  1457. return [];
  1458. }
  1459. if(empty($request->file('file'))) {
  1460. return response('', 422);
  1461. }
  1462. $limitKey = 'compose:rate-limit:media-upload:' . $user->id;
  1463. $limitTtl = now()->addMinutes(15);
  1464. $limitReached = Cache::remember($limitKey, $limitTtl, function() use($user) {
  1465. $dailyLimit = Media::whereUserId($user->id)->where('created_at', '>', now()->subDays(1))->count();
  1466. return $dailyLimit >= 250;
  1467. });
  1468. abort_if($limitReached == true, 429);
  1469. $profile = $user->profile;
  1470. if(config_cache('pixelfed.enforce_account_limit') == true) {
  1471. $size = Cache::remember($user->storageUsedKey(), now()->addDays(3), function() use($user) {
  1472. return Media::whereUserId($user->id)->sum('size') / 1000;
  1473. });
  1474. $limit = (int) config_cache('pixelfed.max_account_size');
  1475. if ($size >= $limit) {
  1476. abort(403, 'Account size limit reached.');
  1477. }
  1478. }
  1479. $filterClass = in_array($request->input('filter_class'), Filter::classes()) ? $request->input('filter_class') : null;
  1480. $filterName = in_array($request->input('filter_name'), Filter::names()) ? $request->input('filter_name') : null;
  1481. $photo = $request->file('file');
  1482. $mimes = explode(',', config_cache('pixelfed.media_types'));
  1483. if(in_array($photo->getMimeType(), $mimes) == false) {
  1484. abort(403, 'Invalid or unsupported mime type.');
  1485. }
  1486. $storagePath = MediaPathService::get($user, 2);
  1487. $path = $photo->storePublicly($storagePath);
  1488. $hash = \hash_file('sha256', $photo);
  1489. $license = null;
  1490. $mime = $photo->getMimeType();
  1491. // if($photo->getMimeType() == 'image/heic') {
  1492. // abort_if(config('image.driver') !== 'imagick', 422, 'Invalid media type');
  1493. // abort_if(!in_array('HEIC', \Imagick::queryformats()), 422, 'Unsupported media type');
  1494. // $oldPath = $path;
  1495. // $path = str_replace('.heic', '.jpg', $path);
  1496. // $mime = 'image/jpeg';
  1497. // \Image::make($photo)->save(storage_path("app/{$path}"));
  1498. // @unlink(storage_path("app/{$oldPath}"));
  1499. // }
  1500. $settings = UserSetting::whereUserId($user->id)->first();
  1501. if($settings && !empty($settings->compose_settings)) {
  1502. $compose = $settings->compose_settings;
  1503. if(isset($compose['default_license']) && $compose['default_license'] != 1) {
  1504. $license = $compose['default_license'];
  1505. }
  1506. }
  1507. abort_if(MediaBlocklistService::exists($hash) == true, 451);
  1508. $media = new Media();
  1509. $media->status_id = null;
  1510. $media->profile_id = $profile->id;
  1511. $media->user_id = $user->id;
  1512. $media->media_path = $path;
  1513. $media->original_sha256 = $hash;
  1514. $media->size = $photo->getSize();
  1515. $media->mime = $mime;
  1516. $media->caption = $request->input('description');
  1517. $media->filter_class = $filterClass;
  1518. $media->filter_name = $filterName;
  1519. if($license) {
  1520. $media->license = $license;
  1521. }
  1522. $media->save();
  1523. switch ($media->mime) {
  1524. case 'image/jpeg':
  1525. case 'image/png':
  1526. ImageOptimize::dispatch($media)->onQueue('mmo');
  1527. break;
  1528. case 'video/mp4':
  1529. VideoThumbnail::dispatch($media)->onQueue('mmo');
  1530. $preview_url = '/storage/no-preview.png';
  1531. $url = '/storage/no-preview.png';
  1532. break;
  1533. }
  1534. Cache::forget($limitKey);
  1535. $resource = new Fractal\Resource\Item($media, new MediaTransformer());
  1536. $res = $this->fractal->createData($resource)->toArray();
  1537. $res['preview_url'] = $media->url(). '?v=' . time();
  1538. $res['url'] = $media->url(). '?v=' . time();
  1539. return $this->json($res);
  1540. }
  1541. /**
  1542. * PUT /api/v1/media/{id}
  1543. *
  1544. * @param integer $id
  1545. *
  1546. * @return MediaTransformer
  1547. */
  1548. public function mediaUpdate(Request $request, $id)
  1549. {
  1550. abort_if(!$request->user(), 403);
  1551. if(config('pixelfed.bouncer.cloud_ips.ban_api')) {
  1552. abort_if(BouncerService::checkIp($request->ip()), 404);
  1553. }
  1554. $this->validate($request, [
  1555. 'description' => 'nullable|string|max:' . config_cache('pixelfed.max_altext_length')
  1556. ]);
  1557. $user = $request->user();
  1558. $media = Media::whereUserId($user->id)
  1559. ->whereProfileId($user->profile_id)
  1560. ->findOrFail($id);
  1561. $executed = RateLimiter::attempt(
  1562. 'media:update:'.$user->id,
  1563. 10,
  1564. function() use($media, $request) {
  1565. $caption = Purify::clean($request->input('description'));
  1566. if($caption != $media->caption) {
  1567. $media->caption = $caption;
  1568. $media->save();
  1569. if($media->status_id) {
  1570. MediaService::del($media->status_id);
  1571. StatusService::del($media->status_id);
  1572. }
  1573. }
  1574. });
  1575. if(!$executed) {
  1576. return response()->json([
  1577. 'error' => 'Too many attempts. Try again in a few minutes.'
  1578. ], 429);
  1579. };
  1580. $fractal = new Fractal\Manager();
  1581. $fractal->setSerializer(new ArraySerializer());
  1582. $resource = new Fractal\Resource\Item($media, new MediaTransformer());
  1583. return $this->json($fractal->createData($resource)->toArray());
  1584. }
  1585. /**
  1586. * GET /api/v1/media/{id}
  1587. *
  1588. * @param integer $id
  1589. *
  1590. * @return MediaTransformer
  1591. */
  1592. public function mediaGet(Request $request, $id)
  1593. {
  1594. abort_if(!$request->user(), 403);
  1595. if(config('pixelfed.bouncer.cloud_ips.ban_api')) {
  1596. abort_if(BouncerService::checkIp($request->ip()), 404);
  1597. }
  1598. $user = $request->user();
  1599. $media = Media::whereUserId($user->id)
  1600. ->whereNull('status_id')
  1601. ->findOrFail($id);
  1602. $resource = new Fractal\Resource\Item($media, new MediaTransformer());
  1603. $res = $this->fractal->createData($resource)->toArray();
  1604. return $this->json($res);
  1605. }
  1606. /**
  1607. * POST /api/v2/media
  1608. *
  1609. *
  1610. * @return MediaTransformer
  1611. */
  1612. public function mediaUploadV2(Request $request)
  1613. {
  1614. abort_if(!$request->user(), 403);
  1615. if(config('pixelfed.bouncer.cloud_ips.ban_api')) {
  1616. abort_if(BouncerService::checkIp($request->ip()), 404);
  1617. }
  1618. $this->validate($request, [
  1619. 'file.*' => [
  1620. 'required_without:file',
  1621. 'mimetypes:' . config_cache('pixelfed.media_types'),
  1622. 'max:' . config_cache('pixelfed.max_photo_size'),
  1623. ],
  1624. 'file' => [
  1625. 'required_without:file.*',
  1626. 'mimetypes:' . config_cache('pixelfed.media_types'),
  1627. 'max:' . config_cache('pixelfed.max_photo_size'),
  1628. ],
  1629. 'filter_name' => 'nullable|string|max:24',
  1630. 'filter_class' => 'nullable|alpha_dash|max:24',
  1631. 'description' => 'nullable|string|max:' . config_cache('pixelfed.max_altext_length'),
  1632. 'replace_id' => 'sometimes'
  1633. ]);
  1634. $user = $request->user();
  1635. if($user->last_active_at == null) {
  1636. return [];
  1637. }
  1638. if(empty($request->file('file'))) {
  1639. return response('', 422);
  1640. }
  1641. $limitKey = 'compose:rate-limit:media-upload:' . $user->id;
  1642. $limitTtl = now()->addMinutes(15);
  1643. $limitReached = Cache::remember($limitKey, $limitTtl, function() use($user) {
  1644. $dailyLimit = Media::whereUserId($user->id)->where('created_at', '>', now()->subDays(1))->count();
  1645. return $dailyLimit >= 250;
  1646. });
  1647. abort_if($limitReached == true, 429);
  1648. $profile = $user->profile;
  1649. if(config_cache('pixelfed.enforce_account_limit') == true) {
  1650. $size = Cache::remember($user->storageUsedKey(), now()->addDays(3), function() use($user) {
  1651. return Media::whereUserId($user->id)->sum('size') / 1000;
  1652. });
  1653. $limit = (int) config_cache('pixelfed.max_account_size');
  1654. if ($size >= $limit) {
  1655. abort(403, 'Account size limit reached.');
  1656. }
  1657. }
  1658. $filterClass = in_array($request->input('filter_class'), Filter::classes()) ? $request->input('filter_class') : null;
  1659. $filterName = in_array($request->input('filter_name'), Filter::names()) ? $request->input('filter_name') : null;
  1660. $photo = $request->file('file');
  1661. $mimes = explode(',', config_cache('pixelfed.media_types'));
  1662. if(in_array($photo->getMimeType(), $mimes) == false) {
  1663. abort(403, 'Invalid or unsupported mime type.');
  1664. }
  1665. $storagePath = MediaPathService::get($user, 2);
  1666. $path = $photo->storePublicly($storagePath);
  1667. $hash = \hash_file('sha256', $photo);
  1668. $license = null;
  1669. $mime = $photo->getMimeType();
  1670. $settings = UserSetting::whereUserId($user->id)->first();
  1671. if($settings && !empty($settings->compose_settings)) {
  1672. $compose = $settings->compose_settings;
  1673. if(isset($compose['default_license']) && $compose['default_license'] != 1) {
  1674. $license = $compose['default_license'];
  1675. }
  1676. }
  1677. abort_if(MediaBlocklistService::exists($hash) == true, 451);
  1678. if($request->has('replace_id')) {
  1679. $rpid = $request->input('replace_id');
  1680. $removeMedia = Media::whereNull('status_id')
  1681. ->whereUserId($user->id)
  1682. ->whereProfileId($profile->id)
  1683. ->where('created_at', '>', now()->subHours(2))
  1684. ->find($rpid);
  1685. if($removeMedia) {
  1686. $dateTime = Carbon::now();
  1687. MediaDeletePipeline::dispatch($removeMedia)
  1688. ->onQueue('mmo')
  1689. ->delay($dateTime->addMinutes(15));
  1690. }
  1691. }
  1692. $media = new Media();
  1693. $media->status_id = null;
  1694. $media->profile_id = $profile->id;
  1695. $media->user_id = $user->id;
  1696. $media->media_path = $path;
  1697. $media->original_sha256 = $hash;
  1698. $media->size = $photo->getSize();
  1699. $media->mime = $mime;
  1700. $media->caption = $request->input('description');
  1701. $media->filter_class = $filterClass;
  1702. $media->filter_name = $filterName;
  1703. if($license) {
  1704. $media->license = $license;
  1705. }
  1706. $media->save();
  1707. switch ($media->mime) {
  1708. case 'image/jpeg':
  1709. case 'image/png':
  1710. ImageOptimize::dispatch($media)->onQueue('mmo');
  1711. break;
  1712. case 'video/mp4':
  1713. VideoThumbnail::dispatch($media)->onQueue('mmo');
  1714. $preview_url = '/storage/no-preview.png';
  1715. $url = '/storage/no-preview.png';
  1716. break;
  1717. }
  1718. Cache::forget($limitKey);
  1719. $resource = new Fractal\Resource\Item($media, new MediaTransformer());
  1720. $res = $this->fractal->createData($resource)->toArray();
  1721. $res['preview_url'] = $media->url(). '?v=' . time();
  1722. $res['url'] = null;
  1723. return $this->json($res, 202);
  1724. }
  1725. /**
  1726. * GET /api/v1/mutes
  1727. *
  1728. *
  1729. * @return AccountTransformer
  1730. */
  1731. public function accountMutes(Request $request)
  1732. {
  1733. abort_if(!$request->user(), 403);
  1734. $this->validate($request, [
  1735. 'limit' => 'nullable|integer|min:1|max:40'
  1736. ]);
  1737. $user = $request->user();
  1738. $limit = $request->input('limit', 40);
  1739. $mutes = UserFilter::whereUserId($user->profile_id)
  1740. ->whereFilterableType('App\Profile')
  1741. ->whereFilterType('mute')
  1742. ->orderByDesc('id')
  1743. ->simplePaginate($limit)
  1744. ->pluck('filterable_id')
  1745. ->map(function($id) {
  1746. return AccountService::get($id, true);
  1747. })
  1748. ->filter(function($account) {
  1749. return $account && isset($account['id']);
  1750. })
  1751. ->values();
  1752. return $this->json($mutes);
  1753. }
  1754. /**
  1755. * POST /api/v1/accounts/{id}/mute
  1756. *
  1757. * @param integer $id
  1758. *
  1759. * @return RelationshipTransformer
  1760. */
  1761. public function accountMuteById(Request $request, $id)
  1762. {
  1763. abort_if(!$request->user(), 403);
  1764. if(config('pixelfed.bouncer.cloud_ips.ban_api')) {
  1765. abort_if(BouncerService::checkIp($request->ip()), 404);
  1766. }
  1767. $user = $request->user();
  1768. $pid = $user->profile_id;
  1769. if(intval($pid) === intval($id)) {
  1770. return $this->json(['error' => 'You cannot mute yourself'], 500);
  1771. }
  1772. $account = Profile::findOrFail($id);
  1773. $count = UserFilterService::muteCount($pid);
  1774. $maxLimit = intval(config('instance.user_filters.max_user_mutes'));
  1775. if($count == 0) {
  1776. $filterCount = UserFilter::whereUserId($pid)
  1777. ->whereFilterType('mute')
  1778. ->get()
  1779. ->map(function($rec) {
  1780. return AccountService::get($rec->filterable_id, true);
  1781. })
  1782. ->filter(function($account) {
  1783. return $account && isset($account['id']);
  1784. })
  1785. ->values()
  1786. ->count();
  1787. abort_if($filterCount >= $maxLimit, 422, AccountController::FILTER_LIMIT_MUTE_TEXT . $maxLimit . ' accounts');
  1788. } else {
  1789. abort_if($count >= $maxLimit, 422, AccountController::FILTER_LIMIT_MUTE_TEXT . $maxLimit . ' accounts');
  1790. }
  1791. $filter = UserFilter::firstOrCreate([
  1792. 'user_id' => $pid,
  1793. 'filterable_id' => $account->id,
  1794. 'filterable_type' => 'App\Profile',
  1795. 'filter_type' => 'mute',
  1796. ]);
  1797. RelationshipService::refresh($pid, $id);
  1798. $resource = new Fractal\Resource\Item($account, new RelationshipTransformer());
  1799. $res = $this->fractal->createData($resource)->toArray();
  1800. return $this->json($res);
  1801. }
  1802. /**
  1803. * POST /api/v1/accounts/{id}/unmute
  1804. *
  1805. * @param integer $id
  1806. *
  1807. * @return RelationshipTransformer
  1808. */
  1809. public function accountUnmuteById(Request $request, $id)
  1810. {
  1811. abort_if(!$request->user(), 403);
  1812. if(config('pixelfed.bouncer.cloud_ips.ban_api')) {
  1813. abort_if(BouncerService::checkIp($request->ip()), 404);
  1814. }
  1815. $user = $request->user();
  1816. $pid = $user->profile_id;
  1817. if(intval($pid) === intval($id)) {
  1818. return $this->json(['error' => 'You cannot unmute yourself'], 500);
  1819. }
  1820. $profile = Profile::findOrFail($id);
  1821. $filter = UserFilter::whereUserId($pid)
  1822. ->whereFilterableId($profile->id)
  1823. ->whereFilterableType('App\Profile')
  1824. ->whereFilterType('mute')
  1825. ->first();
  1826. if($filter) {
  1827. $filter->delete();
  1828. UserFilterService::unmute($pid, $profile->id);
  1829. RelationshipService::refresh($pid, $id);
  1830. }
  1831. $resource = new Fractal\Resource\Item($profile, new RelationshipTransformer());
  1832. $res = $this->fractal->createData($resource)->toArray();
  1833. return $this->json($res);
  1834. }
  1835. /**
  1836. * GET /api/v1/notifications
  1837. *
  1838. *
  1839. * @return NotificationTransformer
  1840. */
  1841. public function accountNotifications(Request $request)
  1842. {
  1843. abort_if(!$request->user(), 403);
  1844. if(config('pixelfed.bouncer.cloud_ips.ban_api_strict_mode')) {
  1845. abort_if(BouncerService::checkIp($request->ip()), 404);
  1846. }
  1847. $this->validate($request, [
  1848. 'limit' => 'nullable|integer|min:1|max:100',
  1849. 'min_id' => 'nullable|integer|min:1|max:'.PHP_INT_MAX,
  1850. 'max_id' => 'nullable|integer|min:1|max:'.PHP_INT_MAX,
  1851. 'since_id' => 'nullable|integer|min:1|max:'.PHP_INT_MAX,
  1852. ]);
  1853. $pid = $request->user()->profile_id;
  1854. $limit = $request->input('limit', 20);
  1855. $since = $request->input('since_id');
  1856. $min = $request->input('min_id');
  1857. $max = $request->input('max_id');
  1858. if(!$since && !$min && !$max) {
  1859. $min = 1;
  1860. }
  1861. $maxId = null;
  1862. $minId = null;
  1863. if($max) {
  1864. $res = NotificationService::getMaxMastodon($pid, $max, $limit);
  1865. $ids = NotificationService::getRankedMaxId($pid, $max, $limit);
  1866. if(!empty($ids)) {
  1867. $maxId = max($ids);
  1868. $minId = min($ids);
  1869. }
  1870. } else {
  1871. $res = NotificationService::getMinMastodon($pid, $min ?? $since, $limit);
  1872. $ids = NotificationService::getRankedMinId($pid, $min ?? $since, $limit);
  1873. if(!empty($ids)) {
  1874. $maxId = max($ids);
  1875. $minId = min($ids);
  1876. }
  1877. }
  1878. if(empty($res) && !Cache::has('pf:services:notifications:hasSynced:'.$pid)) {
  1879. Cache::put('pf:services:notifications:hasSynced:'.$pid, 1, 1209600);
  1880. NotificationService::warmCache($pid, 400, true);
  1881. }
  1882. $baseUrl = config('app.url') . '/api/v1/notifications?limit=' . $limit . '&';
  1883. if($minId == $maxId) {
  1884. $minId = null;
  1885. }
  1886. if($maxId) {
  1887. $link = '<'.$baseUrl.'max_id='.$minId.'>; rel="next"';
  1888. }
  1889. if($minId) {
  1890. $link = '<'.$baseUrl.'min_id='.$maxId.'>; rel="prev"';
  1891. }
  1892. if($maxId && $minId) {
  1893. $link = '<'.$baseUrl.'max_id='.$minId.'>; rel="next",<'.$baseUrl.'min_id='.$maxId.'>; rel="prev"';
  1894. }
  1895. $headers = isset($link) ? ['Link' => $link] : [];
  1896. return $this->json($res, 200, $headers);
  1897. }
  1898. /**
  1899. * GET /api/v1/timelines/home
  1900. *
  1901. *
  1902. * @return StatusTransformer
  1903. */
  1904. public function timelineHome(Request $request)
  1905. {
  1906. $this->validate($request,[
  1907. 'page' => 'sometimes|integer|max:40',
  1908. 'min_id' => 'sometimes|integer|min:0|max:' . PHP_INT_MAX,
  1909. 'max_id' => 'sometimes|integer|min:0|max:' . PHP_INT_MAX,
  1910. 'limit' => 'sometimes|integer|min:1|max:100'
  1911. ]);
  1912. if(config('pixelfed.bouncer.cloud_ips.ban_api_strict_mode')) {
  1913. abort_if(BouncerService::checkIp($request->ip()), 404);
  1914. }
  1915. $napi = $request->has(self::PF_API_ENTITY_KEY);
  1916. $page = $request->input('page');
  1917. $min = $request->input('min_id');
  1918. $max = $request->input('max_id');
  1919. $limit = $request->input('limit') ?? 20;
  1920. $pid = $request->user()->profile_id;
  1921. $following = Cache::remember('profile:following:'.$pid, 1209600, function() use($pid) {
  1922. $following = Follower::whereProfileId($pid)->pluck('following_id');
  1923. return $following->push($pid)->toArray();
  1924. });
  1925. if($min || $max) {
  1926. $dir = $min ? '>' : '<';
  1927. $id = $min ?? $max;
  1928. $res = Status::select(
  1929. 'id',
  1930. 'profile_id',
  1931. 'type',
  1932. 'visibility',
  1933. 'in_reply_to_id',
  1934. 'reblog_of_id'
  1935. )
  1936. ->where('id', $dir, $id)
  1937. ->whereNull(['in_reply_to_id', 'reblog_of_id'])
  1938. ->whereIntegerInRaw('profile_id', $following)
  1939. ->whereIn('type', ['photo', 'photo:album', 'video', 'video:album', 'photo:video:album'])
  1940. ->whereIn('visibility',['public', 'unlisted', 'private'])
  1941. ->orderByDesc('id')
  1942. ->take(($limit * 2))
  1943. ->get()
  1944. ->map(function($s) use($pid, $napi) {
  1945. try {
  1946. $account = $napi ? AccountService::get($s['profile_id'], true) : AccountService::getMastodon($s['profile_id'], true);
  1947. if(!$account) {
  1948. return false;
  1949. }
  1950. $status = $napi ? StatusService::get($s['id'], false) : StatusService::getMastodon($s['id'], false);
  1951. if(!$status || !isset($status['account']) || !isset($status['account']['id'])) {
  1952. return false;
  1953. }
  1954. } catch(\Exception $e) {
  1955. return false;
  1956. }
  1957. $status['account'] = $account;
  1958. if($pid) {
  1959. $status['favourited'] = (bool) LikeService::liked($pid, $s['id']);
  1960. $status['reblogged'] = (bool) ReblogService::get($pid, $status['id']);
  1961. }
  1962. return $status;
  1963. })
  1964. ->filter(function($status) {
  1965. return $status && isset($status['account']);
  1966. })
  1967. ->take($limit)
  1968. ->values();
  1969. } else {
  1970. $res = Status::select(
  1971. 'id',
  1972. 'profile_id',
  1973. 'type',
  1974. 'visibility',
  1975. 'in_reply_to_id',
  1976. 'reblog_of_id',
  1977. )
  1978. ->whereNull(['in_reply_to_id', 'reblog_of_id'])
  1979. ->whereIntegerInRaw('profile_id', $following)
  1980. ->whereIn('type', ['photo', 'photo:album', 'video', 'video:album', 'photo:video:album'])
  1981. ->whereIn('visibility',['public', 'unlisted', 'private'])
  1982. ->orderByDesc('id')
  1983. ->take(($limit * 2))
  1984. ->get()
  1985. ->map(function($s) use($pid, $napi) {
  1986. try {
  1987. $account = $napi ? AccountService::get($s['profile_id'], true) : AccountService::getMastodon($s['profile_id'], true);
  1988. if(!$account) {
  1989. return false;
  1990. }
  1991. $status = $napi ? StatusService::get($s['id'], false) : StatusService::getMastodon($s['id'], false);
  1992. if(!$status || !isset($status['account']) || !isset($status['account']['id'])) {
  1993. return false;
  1994. }
  1995. } catch(\Exception $e) {
  1996. return false;
  1997. }
  1998. $status['account'] = $account;
  1999. if($pid) {
  2000. $status['favourited'] = (bool) LikeService::liked($pid, $s['id']);
  2001. $status['reblogged'] = (bool) ReblogService::get($pid, $status['id']);
  2002. }
  2003. return $status;
  2004. })
  2005. ->filter(function($status) {
  2006. return $status && isset($status['account']);
  2007. })
  2008. ->take($limit)
  2009. ->values();
  2010. }
  2011. $baseUrl = config('app.url') . '/api/v1/timelines/home?limit=' . $limit . '&';
  2012. $minId = $res->map(function($s) {
  2013. return ['id' => $s['id']];
  2014. })->min('id');
  2015. $maxId = $res->map(function($s) {
  2016. return ['id' => $s['id']];
  2017. })->max('id');
  2018. if($minId == $maxId) {
  2019. $minId = null;
  2020. }
  2021. if($maxId) {
  2022. $link = '<'.$baseUrl.'max_id='.$minId.'>; rel="next"';
  2023. }
  2024. if($minId) {
  2025. $link = '<'.$baseUrl.'min_id='.$maxId.'>; rel="prev"';
  2026. }
  2027. if($maxId && $minId) {
  2028. $link = '<'.$baseUrl.'max_id='.$minId.'>; rel="next",<'.$baseUrl.'min_id='.$maxId.'>; rel="prev"';
  2029. }
  2030. $headers = isset($link) ? ['Link' => $link] : [];
  2031. return $this->json($res->toArray(), 200, $headers);
  2032. }
  2033. /**
  2034. * GET /api/v1/timelines/public
  2035. *
  2036. *
  2037. * @return StatusTransformer
  2038. */
  2039. public function timelinePublic(Request $request)
  2040. {
  2041. $this->validate($request,[
  2042. 'min_id' => 'nullable|integer|min:0|max:' . PHP_INT_MAX,
  2043. 'max_id' => 'nullable|integer|min:0|max:' . PHP_INT_MAX,
  2044. 'limit' => 'nullable|integer|max:100',
  2045. 'remote' => 'sometimes',
  2046. 'local' => 'sometimes'
  2047. ]);
  2048. if(config('pixelfed.bouncer.cloud_ips.ban_api_strict_mode')) {
  2049. abort_if(BouncerService::checkIp($request->ip()), 404);
  2050. }
  2051. $napi = $request->has(self::PF_API_ENTITY_KEY);
  2052. $min = $request->input('min_id');
  2053. $max = $request->input('max_id');
  2054. $limit = $request->input('limit') ?? 20;
  2055. $user = $request->user();
  2056. $remote = ($request->has('remote') && $request->input('remote') == true) || ($request->filled('local') && $request->input('local') != true);
  2057. $filtered = $user ? UserFilterService::filters($user->profile_id) : [];
  2058. if((!$request->has('local') || $remote) && config('instance.timeline.network.cached')) {
  2059. Cache::remember('api:v1:timelines:network:cache_check', 10368000, function() {
  2060. if(NetworkTimelineService::count() == 0) {
  2061. NetworkTimelineService::warmCache(true, config('instance.timeline.network.cache_dropoff'));
  2062. }
  2063. });
  2064. if ($max) {
  2065. $feed = NetworkTimelineService::getRankedMaxId($max, $limit + 5);
  2066. } else if ($min) {
  2067. $feed = NetworkTimelineService::getRankedMinId($min, $limit + 5);
  2068. } else {
  2069. $feed = NetworkTimelineService::get(0, $limit + 5);
  2070. }
  2071. } else {
  2072. Cache::remember('api:v1:timelines:public:cache_check', 10368000, function() {
  2073. if(PublicTimelineService::count() == 0) {
  2074. PublicTimelineService::warmCache(true, 400);
  2075. }
  2076. });
  2077. if ($max) {
  2078. $feed = PublicTimelineService::getRankedMaxId($max, $limit + 5);
  2079. } else if ($min) {
  2080. $feed = PublicTimelineService::getRankedMinId($min, $limit + 5);
  2081. } else {
  2082. $feed = PublicTimelineService::get(0, $limit + 5);
  2083. }
  2084. }
  2085. $res = collect($feed)
  2086. ->filter(function($k) use($min, $max) {
  2087. if(!$min && !$max) {
  2088. return true;
  2089. }
  2090. if($min) {
  2091. return $min != $k;
  2092. }
  2093. if($max) {
  2094. return $max != $k;
  2095. }
  2096. })
  2097. ->map(function($k) use($user, $napi) {
  2098. try {
  2099. $status = $napi ? StatusService::get($k) : StatusService::getMastodon($k);
  2100. if(!$status || !isset($status['account']) || !isset($status['account']['id'])) {
  2101. return false;
  2102. }
  2103. } catch(\Exception $e) {
  2104. return false;
  2105. }
  2106. $account = $napi ? AccountService::get($status['account']['id'], true) : AccountService::getMastodon($status['account']['id'], true);
  2107. if(!$account) {
  2108. return false;
  2109. }
  2110. $status['account'] = $account;
  2111. if($user) {
  2112. $status['favourited'] = (bool) LikeService::liked($user->profile_id, $k);
  2113. $status['reblogged'] = (bool) ReblogService::get($user->profile_id, $status['id']);
  2114. }
  2115. return $status;
  2116. })
  2117. ->filter(function($s) use($filtered) {
  2118. return $s && isset($s['account']) && in_array($s['account']['id'], $filtered) == false;
  2119. })
  2120. ->take($limit)
  2121. ->values();
  2122. $baseUrl = config('app.url') . '/api/v1/timelines/public?limit=' . $limit . '&';
  2123. if($remote) {
  2124. $baseUrl .= 'remote=1&';
  2125. }
  2126. $minId = $res->map(function($s) {
  2127. return ['id' => $s['id']];
  2128. })->min('id');
  2129. $maxId = $res->map(function($s) {
  2130. return ['id' => $s['id']];
  2131. })->max('id');
  2132. if($minId == $maxId) {
  2133. $minId = null;
  2134. }
  2135. if($maxId) {
  2136. $link = '<'.$baseUrl.'max_id='.$minId.'>; rel="next"';
  2137. }
  2138. if($minId) {
  2139. $link = '<'.$baseUrl.'min_id='.$maxId.'>; rel="prev"';
  2140. }
  2141. if($maxId && $minId) {
  2142. $link = '<'.$baseUrl.'max_id='.$minId.'>; rel="next",<'.$baseUrl.'min_id='.$maxId.'>; rel="prev"';
  2143. }
  2144. $headers = isset($link) ? ['Link' => $link] : [];
  2145. return $this->json($res->toArray(), 200, $headers);
  2146. }
  2147. /**
  2148. * GET /api/v1/conversations
  2149. *
  2150. * Not implemented
  2151. *
  2152. * @return array
  2153. */
  2154. public function conversations(Request $request)
  2155. {
  2156. abort_if(!$request->user(), 403);
  2157. $this->validate($request, [
  2158. 'limit' => 'min:1|max:40',
  2159. 'scope' => 'nullable|in:inbox,sent,requests'
  2160. ]);
  2161. if(config('pixelfed.bouncer.cloud_ips.ban_api_strict_mode')) {
  2162. abort_if(BouncerService::checkIp($request->ip()), 404);
  2163. }
  2164. $limit = $request->input('limit', 20);
  2165. $scope = $request->input('scope', 'inbox');
  2166. $pid = $request->user()->profile_id;
  2167. if(config('database.default') == 'pgsql') {
  2168. $dms = DirectMessage::when($scope === 'inbox', function($q, $scope) use($pid) {
  2169. return $q->whereIsHidden(false)->where('to_id', $pid)->orWhere('from_id', $pid);
  2170. })
  2171. ->when($scope === 'sent', function($q, $scope) use($pid) {
  2172. return $q->whereFromId($pid)->groupBy(['to_id', 'id']);
  2173. })
  2174. ->when($scope === 'requests', function($q, $scope) use($pid) {
  2175. return $q->whereToId($pid)->whereIsHidden(true);
  2176. });
  2177. } else {
  2178. $dms = Conversation::when($scope === 'inbox', function($q, $scope) use($pid) {
  2179. return $q->whereIsHidden(false)
  2180. ->where('to_id', $pid)
  2181. ->orWhere('from_id', $pid)
  2182. ->orderByDesc('status_id')
  2183. ->groupBy(['to_id', 'from_id']);
  2184. })
  2185. ->when($scope === 'sent', function($q, $scope) use($pid) {
  2186. return $q->whereFromId($pid)->groupBy('to_id');
  2187. })
  2188. ->when($scope === 'requests', function($q, $scope) use($pid) {
  2189. return $q->whereToId($pid)->whereIsHidden(true);
  2190. });
  2191. }
  2192. $dms = $dms->orderByDesc('status_id')
  2193. ->simplePaginate($limit)
  2194. ->map(function($dm) use($pid) {
  2195. $from = $pid == $dm->to_id ? $dm->from_id : $dm->to_id;
  2196. $res = [
  2197. 'id' => $dm->id,
  2198. 'unread' => false,
  2199. 'accounts' => [
  2200. AccountService::getMastodon($from)
  2201. ],
  2202. 'last_status' => StatusService::getDirectMessage($dm->status_id)
  2203. ];
  2204. return $res;
  2205. })
  2206. ->filter(function($dm) {
  2207. return isset($dm['accounts']) && count($dm['accounts']) && !empty($dm['last_status']);
  2208. })
  2209. ->unique(function($item, $key) {
  2210. return $item['accounts'][0]['id'];
  2211. })
  2212. ->values();
  2213. return $this->json($dms);
  2214. }
  2215. /**
  2216. * GET /api/v1/statuses/{id}
  2217. *
  2218. * @param integer $id
  2219. *
  2220. * @return StatusTransformer
  2221. */
  2222. public function statusById(Request $request, $id)
  2223. {
  2224. abort_if(!$request->user(), 403);
  2225. if(config('pixelfed.bouncer.cloud_ips.ban_api_strict_mode')) {
  2226. abort_if(BouncerService::checkIp($request->ip()), 404);
  2227. }
  2228. $user = $request->user();
  2229. $res = $request->has(self::PF_API_ENTITY_KEY) ? StatusService::get($id, false) : StatusService::getMastodon($id, false);
  2230. if(!$res || !isset($res['visibility'])) {
  2231. abort(404);
  2232. }
  2233. $scope = $res['visibility'];
  2234. if(!in_array($scope, ['public', 'unlisted'])) {
  2235. if($scope === 'private') {
  2236. if(intval($res['account']['id']) !== intval($user->profile_id)) {
  2237. abort_unless(FollowerService::follows($user->profile_id, $res['account']['id']), 403);
  2238. }
  2239. } else {
  2240. abort(400, 'Invalid request');
  2241. }
  2242. }
  2243. $res['favourited'] = LikeService::liked($user->profile_id, $res['id']);
  2244. $res['reblogged'] = ReblogService::get($user->profile_id, $res['id']);
  2245. $res['bookmarked'] = BookmarkService::get($user->profile_id, $res['id']);
  2246. return $this->json($res);
  2247. }
  2248. /**
  2249. * GET /api/v1/statuses/{id}/context
  2250. *
  2251. * @param integer $id
  2252. *
  2253. * @return StatusTransformer
  2254. */
  2255. public function statusContext(Request $request, $id)
  2256. {
  2257. abort_if(!$request->user(), 403);
  2258. if(config('pixelfed.bouncer.cloud_ips.ban_api_strict_mode')) {
  2259. abort_if(BouncerService::checkIp($request->ip()), 404);
  2260. }
  2261. $user = $request->user();
  2262. $pid = $user->profile_id;
  2263. $status = StatusService::getMastodon($id, false);
  2264. if(!$status || !isset($status['account'])) {
  2265. return response('', 404);
  2266. }
  2267. if(intval($status['account']['id']) !== intval($user->profile_id)) {
  2268. if($status['visibility'] == 'private') {
  2269. if(!FollowerService::follows($user->profile_id, $status['account']['id'])) {
  2270. return response('', 404);
  2271. }
  2272. } else {
  2273. if(!in_array($status['visibility'], ['public','unlisted'])) {
  2274. return response('', 404);
  2275. }
  2276. }
  2277. }
  2278. $ancestors = [];
  2279. $descendants = [];
  2280. if($status['in_reply_to_id']) {
  2281. $ancestors[] = StatusService::getMastodon($status['in_reply_to_id'], false);
  2282. }
  2283. if($status['replies_count']) {
  2284. $filters = UserFilterService::filters($pid);
  2285. $descendants = DB::table('statuses')
  2286. ->where('in_reply_to_id', $id)
  2287. ->limit(20)
  2288. ->pluck('id')
  2289. ->map(function($sid) {
  2290. return StatusService::getMastodon($sid, false);
  2291. })
  2292. ->filter(function($post) use($filters) {
  2293. return $post && isset($post['account'], $post['account']['id']) && !in_array($post['account']['id'], $filters);
  2294. })
  2295. ->map(function($status) use($pid) {
  2296. $status['favourited'] = LikeService::liked($pid, $status['id']);
  2297. $status['reblogged'] = ReblogService::get($pid, $status['id']);
  2298. return $status;
  2299. })
  2300. ->values();
  2301. }
  2302. $res = [
  2303. 'ancestors' => $ancestors,
  2304. 'descendants' => $descendants
  2305. ];
  2306. return $this->json($res);
  2307. }
  2308. /**
  2309. * GET /api/v1/statuses/{id}/card
  2310. *
  2311. * @param integer $id
  2312. *
  2313. * @return StatusTransformer
  2314. */
  2315. public function statusCard(Request $request, $id)
  2316. {
  2317. abort_if(!$request->user(), 403);
  2318. $res = [];
  2319. return response()->json($res);
  2320. }
  2321. /**
  2322. * GET /api/v1/statuses/{id}/reblogged_by
  2323. *
  2324. * @param integer $id
  2325. *
  2326. * @return AccountTransformer
  2327. */
  2328. public function statusRebloggedBy(Request $request, $id)
  2329. {
  2330. abort_if(!$request->user(), 403);
  2331. $this->validate($request, [
  2332. 'limit' => 'sometimes|integer|min:1|max:80'
  2333. ]);
  2334. if(config('pixelfed.bouncer.cloud_ips.ban_api')) {
  2335. abort_if(BouncerService::checkIp($request->ip()), 404);
  2336. }
  2337. $limit = $request->input('limit', 10);
  2338. $user = $request->user();
  2339. $pid = $user->profile_id;
  2340. $status = Status::findOrFail($id);
  2341. $account = AccountService::get($status->profile_id, true);
  2342. abort_if(!$account, 404);
  2343. $author = intval($status->profile_id) === intval($pid) || $user->is_admin;
  2344. $napi = $request->has(self::PF_API_ENTITY_KEY);
  2345. abort_if(
  2346. !$status->type ||
  2347. !in_array($status->type, ['photo','photo:album', 'photo:video:album', 'reply', 'text', 'video', 'video:album']),
  2348. 404,
  2349. );
  2350. if(!$author) {
  2351. if($status->scope == 'private') {
  2352. abort_if(!FollowerService::follows($pid, $status->profile_id), 403);
  2353. } else {
  2354. abort_if(!in_array($status->scope, ['public','unlisted']), 403);
  2355. }
  2356. if($request->has('cursor')) {
  2357. return $this->json([]);
  2358. }
  2359. }
  2360. $res = Status::where('reblog_of_id', $status->id)
  2361. ->orderByDesc('id')
  2362. ->cursorPaginate($limit)
  2363. ->withQueryString();
  2364. if(!$res) {
  2365. return $this->json([]);
  2366. }
  2367. $headers = [];
  2368. if($author && $res->hasPages()) {
  2369. $links = '';
  2370. if($res->onFirstPage()) {
  2371. if($res->nextPageUrl()) {
  2372. $links = '<' . $res->nextPageUrl() .'>; rel="prev"';
  2373. }
  2374. } else {
  2375. if($res->previousPageUrl()) {
  2376. $links = '<' . $res->previousPageUrl() .'>; rel="next"';
  2377. }
  2378. if($res->nextPageUrl()) {
  2379. if(!empty($links)) {
  2380. $links .= ', ';
  2381. }
  2382. $links .= '<' . $res->nextPageUrl() .'>; rel="prev"';
  2383. }
  2384. }
  2385. $headers = ['Link' => $links];
  2386. }
  2387. $res = $res->map(function($status) use($pid, $napi) {
  2388. $account = $napi ? AccountService::get($status->profile_id, true) : AccountService::getMastodon($status->profile_id, true);
  2389. if(!$account) {
  2390. return false;
  2391. }
  2392. if($napi) {
  2393. $account['follows'] = $status->profile_id == $pid ? null : FollowerService::follows($pid, $status->profile_id);
  2394. }
  2395. return $account;
  2396. })
  2397. ->filter(function($account) {
  2398. return $account && isset($account['id']);
  2399. })
  2400. ->values();
  2401. return $this->json($res, 200, $headers);
  2402. }
  2403. /**
  2404. * GET /api/v1/statuses/{id}/favourited_by
  2405. *
  2406. * @param integer $id
  2407. *
  2408. * @return AccountTransformer
  2409. */
  2410. public function statusFavouritedBy(Request $request, $id)
  2411. {
  2412. abort_if(!$request->user(), 403);
  2413. $this->validate($request, [
  2414. 'limit' => 'nullable|integer|min:1|max:80'
  2415. ]);
  2416. if(config('pixelfed.bouncer.cloud_ips.ban_api')) {
  2417. abort_if(BouncerService::checkIp($request->ip()), 404);
  2418. }
  2419. $limit = $request->input('limit', 10);
  2420. $user = $request->user();
  2421. $pid = $user->profile_id;
  2422. $status = Status::findOrFail($id);
  2423. $account = AccountService::get($status->profile_id, true);
  2424. abort_if(!$account, 404);
  2425. $author = intval($status->profile_id) === intval($pid) || $user->is_admin;
  2426. $napi = $request->has(self::PF_API_ENTITY_KEY);
  2427. abort_if(
  2428. !$status->type ||
  2429. !in_array($status->type, ['photo','photo:album', 'photo:video:album', 'reply', 'text', 'video', 'video:album']),
  2430. 404,
  2431. );
  2432. if(!$author) {
  2433. if($status->scope == 'private') {
  2434. abort_if(!FollowerService::follows($pid, $status->profile_id), 403);
  2435. } else {
  2436. abort_if(!in_array($status->scope, ['public','unlisted']), 403);
  2437. }
  2438. if($request->has('cursor')) {
  2439. return $this->json([]);
  2440. }
  2441. }
  2442. $res = Like::where('status_id', $status->id)
  2443. ->orderByDesc('id')
  2444. ->cursorPaginate($limit)
  2445. ->withQueryString();
  2446. if(!$res) {
  2447. return $this->json([]);
  2448. }
  2449. $headers = [];
  2450. if($author && $res->hasPages()) {
  2451. $links = '';
  2452. if($res->onFirstPage()) {
  2453. if($res->nextPageUrl()) {
  2454. $links = '<' . $res->nextPageUrl() .'>; rel="prev"';
  2455. }
  2456. } else {
  2457. if($res->previousPageUrl()) {
  2458. $links = '<' . $res->previousPageUrl() .'>; rel="next"';
  2459. }
  2460. if($res->nextPageUrl()) {
  2461. if(!empty($links)) {
  2462. $links .= ', ';
  2463. }
  2464. $links .= '<' . $res->nextPageUrl() .'>; rel="prev"';
  2465. }
  2466. }
  2467. $headers = ['Link' => $links];
  2468. }
  2469. $res = $res->map(function($like) use($pid, $napi) {
  2470. $account = $napi ? AccountService::get($like->profile_id, true) : AccountService::getMastodon($like->profile_id, true);
  2471. if(!$account) {
  2472. return false;
  2473. }
  2474. if($napi) {
  2475. $account['follows'] = $like->profile_id == $pid ? null : FollowerService::follows($pid, $like->profile_id);
  2476. }
  2477. return $account;
  2478. })
  2479. ->filter(function($account) {
  2480. return $account && isset($account['id']);
  2481. })
  2482. ->values();
  2483. return $this->json($res, 200, $headers);
  2484. }
  2485. /**
  2486. * POST /api/v1/statuses
  2487. *
  2488. *
  2489. * @return StatusTransformer
  2490. */
  2491. public function statusCreate(Request $request)
  2492. {
  2493. abort_if(!$request->user(), 403);
  2494. if(config('pixelfed.bouncer.cloud_ips.ban_api')) {
  2495. abort_if(BouncerService::checkIp($request->ip()), 404);
  2496. }
  2497. $this->validate($request, [
  2498. 'status' => 'nullable|string',
  2499. 'in_reply_to_id' => 'nullable',
  2500. 'media_ids' => 'sometimes|array|max:' . config_cache('pixelfed.max_album_length'),
  2501. 'sensitive' => 'nullable',
  2502. 'visibility' => 'string|in:private,unlisted,public',
  2503. 'spoiler_text' => 'sometimes|max:140',
  2504. 'place_id' => 'sometimes|integer|min:1|max:128769',
  2505. 'collection_ids' => 'sometimes|array|max:3',
  2506. 'comments_disabled' => 'sometimes|boolean',
  2507. ]);
  2508. if(config('costar.enabled') == true) {
  2509. $blockedKeywords = config('costar.keyword.block');
  2510. if($blockedKeywords !== null && $request->status) {
  2511. $keywords = config('costar.keyword.block');
  2512. foreach($keywords as $kw) {
  2513. if(Str::contains($request->status, $kw) == true) {
  2514. abort(400, 'Invalid object. Contains banned keyword.');
  2515. }
  2516. }
  2517. }
  2518. }
  2519. if(!$request->filled('media_ids') && !$request->filled('in_reply_to_id')) {
  2520. abort(403, 'Empty statuses are not allowed');
  2521. }
  2522. $ids = $request->input('media_ids');
  2523. $in_reply_to_id = $request->input('in_reply_to_id');
  2524. $user = $request->user();
  2525. $profile = $user->profile;
  2526. $limitKey = 'compose:rate-limit:store:' . $user->id;
  2527. $limitTtl = now()->addMinutes(15);
  2528. $limitReached = Cache::remember($limitKey, $limitTtl, function() use($user) {
  2529. $dailyLimit = Status::whereProfileId($user->profile_id)
  2530. ->whereNull('in_reply_to_id')
  2531. ->whereNull('reblog_of_id')
  2532. ->where('created_at', '>', now()->subDays(1))
  2533. ->count();
  2534. return $dailyLimit >= 100;
  2535. });
  2536. abort_if($limitReached == true, 429);
  2537. $visibility = $profile->is_private ? 'private' : (
  2538. $profile->unlisted == true &&
  2539. $request->input('visibility', 'public') == 'public' ?
  2540. 'unlisted' :
  2541. $request->input('visibility', 'public'));
  2542. if($user->last_active_at == null) {
  2543. return [];
  2544. }
  2545. $content = strip_tags($request->input('status'));
  2546. $rendered = Autolink::create()->autolink($content);
  2547. $cw = $user->profile->cw == true ? true : $request->input('sensitive', false);
  2548. $spoilerText = $cw && $request->filled('spoiler_text') ? $request->input('spoiler_text') : null;
  2549. if($in_reply_to_id) {
  2550. $parent = Status::findOrFail($in_reply_to_id);
  2551. if($parent->comments_disabled) {
  2552. return $this->json("Comments have been disabled on this post", 422);
  2553. }
  2554. $blocks = UserFilterService::blocks($parent->profile_id);
  2555. abort_if(in_array($profile->id, $blocks), 422, 'Cannot reply to this post at this time.');
  2556. $status = new Status;
  2557. $status->caption = $content;
  2558. $status->rendered = $rendered;
  2559. $status->scope = $visibility;
  2560. $status->visibility = $visibility;
  2561. $status->profile_id = $user->profile_id;
  2562. $status->is_nsfw = $cw;
  2563. $status->cw_summary = $spoilerText;
  2564. $status->in_reply_to_id = $parent->id;
  2565. $status->in_reply_to_profile_id = $parent->profile_id;
  2566. $status->save();
  2567. StatusService::del($parent->id);
  2568. Cache::forget('status:replies:all:' . $parent->id);
  2569. }
  2570. if($ids) {
  2571. if(Media::whereUserId($user->id)
  2572. ->whereNull('status_id')
  2573. ->find($ids)
  2574. ->count() == 0
  2575. ) {
  2576. abort(400, 'Invalid media_ids');
  2577. }
  2578. if(!$in_reply_to_id) {
  2579. $status = new Status;
  2580. $status->caption = $content;
  2581. $status->rendered = $rendered;
  2582. $status->profile_id = $user->profile_id;
  2583. $status->scope = 'draft';
  2584. $status->is_nsfw = $cw;
  2585. $status->cw_summary = $spoilerText;
  2586. if($request->has('place_id')) {
  2587. $status->place_id = $request->input('place_id');
  2588. }
  2589. $status->save();
  2590. }
  2591. $mimes = [];
  2592. foreach($ids as $k => $v) {
  2593. if($k + 1 > config_cache('pixelfed.max_album_length')) {
  2594. continue;
  2595. }
  2596. $m = Media::whereUserId($user->id)->whereNull('status_id')->findOrFail($v);
  2597. if($m->profile_id !== $user->profile_id || $m->status_id) {
  2598. abort(403, 'Invalid media id');
  2599. }
  2600. $m->order = $k + 1;
  2601. $m->status_id = $status->id;
  2602. $m->save();
  2603. array_push($mimes, $m->mime);
  2604. }
  2605. if(empty($mimes)) {
  2606. $status->delete();
  2607. abort(400, 'Invalid media ids');
  2608. }
  2609. if($request->has('comments_disabled') && $request->input('comments_disabled')) {
  2610. $status->comments_disabled = true;
  2611. }
  2612. $status->scope = $visibility;
  2613. $status->visibility = $visibility;
  2614. $status->type = StatusController::mimeTypeCheck($mimes);
  2615. $status->save();
  2616. }
  2617. if(!$status) {
  2618. abort(500, 'An error occured.');
  2619. }
  2620. NewStatusPipeline::dispatch($status);
  2621. if($status->in_reply_to_id) {
  2622. CommentPipeline::dispatch($parent, $status);
  2623. }
  2624. Cache::forget('user:account:id:'.$user->id);
  2625. Cache::forget('_api:statuses:recent_9:'.$user->profile_id);
  2626. Cache::forget('profile:status_count:'.$user->profile_id);
  2627. Cache::forget($user->storageUsedKey());
  2628. Cache::forget('profile:embed:' . $status->profile_id);
  2629. Cache::forget($limitKey);
  2630. if($request->has('collection_ids') && $ids) {
  2631. $collections = Collection::whereProfileId($user->profile_id)
  2632. ->find($request->input('collection_ids'))
  2633. ->each(function($collection) use($status) {
  2634. $count = $collection->items()->count();
  2635. $item = CollectionItem::firstOrCreate([
  2636. 'collection_id' => $collection->id,
  2637. 'object_type' => 'App\Status',
  2638. 'object_id' => $status->id
  2639. ],[
  2640. 'order' => $count,
  2641. ]);
  2642. CollectionService::addItem(
  2643. $collection->id,
  2644. $status->id,
  2645. $count
  2646. );
  2647. $collection->updated_at = now();
  2648. $collection->save();
  2649. CollectionService::setCollection($collection->id, $collection);
  2650. });
  2651. }
  2652. $res = StatusService::getMastodon($status->id, false);
  2653. $res['favourited'] = false;
  2654. $res['language'] = 'en';
  2655. $res['bookmarked'] = false;
  2656. $res['card'] = null;
  2657. return $this->json($res);
  2658. }
  2659. /**
  2660. * DELETE /api/v1/statuses
  2661. *
  2662. * @param integer $id
  2663. *
  2664. * @return null
  2665. */
  2666. public function statusDelete(Request $request, $id)
  2667. {
  2668. abort_if(!$request->user(), 403);
  2669. if(config('pixelfed.bouncer.cloud_ips.ban_api')) {
  2670. abort_if(BouncerService::checkIp($request->ip()), 404);
  2671. }
  2672. $status = Status::whereProfileId($request->user()->profile->id)
  2673. ->findOrFail($id);
  2674. $resource = new Fractal\Resource\Item($status, new StatusTransformer());
  2675. Cache::forget('profile:status_count:'.$status->profile_id);
  2676. StatusDelete::dispatch($status);
  2677. $res = $this->fractal->createData($resource)->toArray();
  2678. $res['text'] = $res['content'];
  2679. unset($res['content']);
  2680. return $this->json($res);
  2681. }
  2682. /**
  2683. * POST /api/v1/statuses/{id}/reblog
  2684. *
  2685. * @param integer $id
  2686. *
  2687. * @return StatusTransformer
  2688. */
  2689. public function statusShare(Request $request, $id)
  2690. {
  2691. abort_if(!$request->user(), 403);
  2692. if(config('pixelfed.bouncer.cloud_ips.ban_api')) {
  2693. abort_if(BouncerService::checkIp($request->ip()), 404);
  2694. }
  2695. $user = $request->user();
  2696. $status = Status::whereScope('public')->findOrFail($id);
  2697. if(intval($status->profile_id) !== intval($user->profile_id)) {
  2698. if($status->scope == 'private') {
  2699. abort_if(!FollowerService::follows($user->profile_id, $status->profile_id), 403);
  2700. } else {
  2701. abort_if(!in_array($status->scope, ['public','unlisted']), 403);
  2702. }
  2703. $blocks = UserFilterService::blocks($status->profile_id);
  2704. if($blocks && in_array($user->profile_id, $blocks)) {
  2705. abort(422);
  2706. }
  2707. }
  2708. $share = Status::firstOrCreate([
  2709. 'profile_id' => $user->profile_id,
  2710. 'reblog_of_id' => $status->id,
  2711. 'type' => 'share',
  2712. 'in_reply_to_profile_id' => $status->profile_id,
  2713. 'scope' => 'public',
  2714. 'visibility' => 'public'
  2715. ]);
  2716. SharePipeline::dispatch($share)->onQueue('low');
  2717. StatusService::del($status->id);
  2718. ReblogService::add($user->profile_id, $status->id);
  2719. $res = StatusService::getMastodon($status->id);
  2720. $res['reblogged'] = true;
  2721. return $this->json($res);
  2722. }
  2723. /**
  2724. * POST /api/v1/statuses/{id}/unreblog
  2725. *
  2726. * @param integer $id
  2727. *
  2728. * @return StatusTransformer
  2729. */
  2730. public function statusUnshare(Request $request, $id)
  2731. {
  2732. abort_if(!$request->user(), 403);
  2733. if(config('pixelfed.bouncer.cloud_ips.ban_api')) {
  2734. abort_if(BouncerService::checkIp($request->ip()), 404);
  2735. }
  2736. $user = $request->user();
  2737. $status = Status::whereScope('public')->findOrFail($id);
  2738. if(intval($status->profile_id) !== intval($user->profile_id)) {
  2739. if($status->scope == 'private') {
  2740. abort_if(!FollowerService::follows($user->profile_id, $status->profile_id), 403);
  2741. } else {
  2742. abort_if(!in_array($status->scope, ['public','unlisted']), 403);
  2743. }
  2744. }
  2745. $reblog = Status::whereProfileId($user->profile_id)
  2746. ->whereReblogOfId($status->id)
  2747. ->first();
  2748. if(!$reblog) {
  2749. $res = StatusService::getMastodon($status->id);
  2750. $res['reblogged'] = false;
  2751. return $this->json($res);
  2752. }
  2753. UndoSharePipeline::dispatch($reblog)->onQueue('low');
  2754. ReblogService::del($user->profile_id, $status->id);
  2755. $res = StatusService::getMastodon($status->id);
  2756. $res['reblogged'] = false;
  2757. return $this->json($res);
  2758. }
  2759. /**
  2760. * GET /api/v1/timelines/tag/{hashtag}
  2761. *
  2762. * @param string $hashtag
  2763. *
  2764. * @return StatusTransformer
  2765. */
  2766. public function timelineHashtag(Request $request, $hashtag)
  2767. {
  2768. abort_if(!$request->user(), 403);
  2769. if(config('pixelfed.bouncer.cloud_ips.ban_api')) {
  2770. abort_if(BouncerService::checkIp($request->ip()), 404);
  2771. }
  2772. $this->validate($request,[
  2773. 'page' => 'nullable|integer|max:40',
  2774. 'min_id' => 'nullable|integer|min:0|max:' . PHP_INT_MAX,
  2775. 'max_id' => 'nullable|integer|min:0|max:' . PHP_INT_MAX,
  2776. 'limit' => 'nullable|integer|max:100'
  2777. ]);
  2778. $tag = Hashtag::whereName($hashtag)
  2779. ->orWhere('slug', $hashtag)
  2780. ->first();
  2781. if(!$tag) {
  2782. return response()->json([]);
  2783. }
  2784. if($tag->is_banned == true) {
  2785. return $this->json([]);
  2786. }
  2787. $min = $request->input('min_id');
  2788. $max = $request->input('max_id');
  2789. $limit = $request->input('limit', 20);
  2790. if(!$min && !$max) {
  2791. $id = 1;
  2792. $dir = '>';
  2793. } else {
  2794. $dir = $min ? '>' : '<';
  2795. $id = $min ?? $max;
  2796. }
  2797. $res = StatusHashtag::whereHashtagId($tag->id)
  2798. ->whereStatusVisibility('public')
  2799. ->where('status_id', $dir, $id)
  2800. ->latest()
  2801. ->limit($limit)
  2802. ->pluck('status_id')
  2803. ->map(function ($i) {
  2804. if($i) {
  2805. return StatusService::getMastodon($i);
  2806. }
  2807. })
  2808. ->filter(function($i) {
  2809. return $i && isset($i['account']);
  2810. })
  2811. ->values()
  2812. ->toArray();
  2813. return $this->json($res);
  2814. }
  2815. /**
  2816. * GET /api/v1/bookmarks
  2817. *
  2818. *
  2819. *
  2820. * @return StatusTransformer
  2821. */
  2822. public function bookmarks(Request $request)
  2823. {
  2824. abort_if(!$request->user(), 403);
  2825. if(config('pixelfed.bouncer.cloud_ips.ban_api')) {
  2826. abort_if(BouncerService::checkIp($request->ip()), 404);
  2827. }
  2828. $this->validate($request, [
  2829. 'limit' => 'nullable|integer|min:1|max:40',
  2830. 'max_id' => 'nullable|integer|min:0',
  2831. 'since_id' => 'nullable|integer|min:0',
  2832. 'min_id' => 'nullable|integer|min:0'
  2833. ]);
  2834. $pe = $request->has('_pe');
  2835. $pid = $request->user()->profile_id;
  2836. $limit = $request->input('limit') ?? 20;
  2837. $max_id = $request->input('max_id');
  2838. $since_id = $request->input('since_id');
  2839. $min_id = $request->input('min_id');
  2840. $dir = $min_id ? '>' : '<';
  2841. $id = $min_id ?? $max_id;
  2842. $bookmarkQuery = Bookmark::whereProfileId($pid)
  2843. ->orderByDesc('id')
  2844. ->cursorPaginate($limit);
  2845. $bookmarks = $bookmarkQuery->map(function($bookmark) use($pid, $pe) {
  2846. $status = $pe ? StatusService::get($bookmark->status_id, false) : StatusService::getMastodon($bookmark->status_id, false);
  2847. if($status) {
  2848. $status['bookmarked'] = true;
  2849. $status['favourited'] = LikeService::liked($pid, $status['id']);
  2850. $status['reblogged'] = ReblogService::get($pid, $status['id']);
  2851. }
  2852. return $status;
  2853. })
  2854. ->filter()
  2855. ->values()
  2856. ->toArray();
  2857. $links = null;
  2858. $headers = [];
  2859. if($bookmarkQuery->nextCursor()) {
  2860. $links .= '<'.$bookmarkQuery->nextPageUrl().'&limit='.$limit.'>; rel="next"';
  2861. }
  2862. if($bookmarkQuery->previousCursor()) {
  2863. if($links != null) {
  2864. $links .= ', ';
  2865. }
  2866. $links .= '<'.$bookmarkQuery->previousPageUrl().'&limit='.$limit.'>; rel="prev"';
  2867. }
  2868. if($links) {
  2869. $headers = ['Link' => $links];
  2870. }
  2871. return $this->json($bookmarks, 200, $headers);
  2872. }
  2873. /**
  2874. * POST /api/v1/statuses/{id}/bookmark
  2875. *
  2876. *
  2877. *
  2878. * @return StatusTransformer
  2879. */
  2880. public function bookmarkStatus(Request $request, $id)
  2881. {
  2882. abort_if(!$request->user(), 403);
  2883. if(config('pixelfed.bouncer.cloud_ips.ban_api')) {
  2884. abort_if(BouncerService::checkIp($request->ip()), 404);
  2885. }
  2886. $status = Status::findOrFail($id);
  2887. $pid = $request->user()->profile_id;
  2888. abort_if($status->in_reply_to_id || $status->reblog_of_id, 404);
  2889. abort_if(!in_array($status->scope, ['public', 'unlisted', 'private']), 404);
  2890. abort_if(!in_array($status->type, ['photo','photo:album', 'video', 'video:album', 'photo:video:album']), 404);
  2891. if($status->scope == 'private') {
  2892. abort_if(
  2893. $pid !== $status->profile_id && !FollowerService::follows($pid, $status->profile_id),
  2894. 404,
  2895. 'Error: You cannot bookmark private posts from accounts you do not follow.'
  2896. );
  2897. }
  2898. Bookmark::firstOrCreate([
  2899. 'status_id' => $status->id,
  2900. 'profile_id' => $pid
  2901. ]);
  2902. BookmarkService::add($pid, $status->id);
  2903. $res = StatusService::getMastodon($status->id, false);
  2904. $res['bookmarked'] = true;
  2905. return $this->json($res);
  2906. }
  2907. /**
  2908. * POST /api/v1/statuses/{id}/unbookmark
  2909. *
  2910. *
  2911. *
  2912. * @return StatusTransformer
  2913. */
  2914. public function unbookmarkStatus(Request $request, $id)
  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. $status = Status::findOrFail($id);
  2921. $pid = $request->user()->profile_id;
  2922. abort_if($status->in_reply_to_id || $status->reblog_of_id, 404);
  2923. abort_if(!in_array($status->scope, ['public', 'unlisted', 'private']), 404);
  2924. abort_if(!in_array($status->type, ['photo','photo:album', 'video', 'video:album', 'photo:video:album']), 404);
  2925. $bookmark = Bookmark::whereStatusId($status->id)
  2926. ->whereProfileId($pid)
  2927. ->first();
  2928. if($bookmark) {
  2929. BookmarkService::del($pid, $status->id);
  2930. $bookmark->delete();
  2931. }
  2932. $res = StatusService::getMastodon($status->id, false);
  2933. $res['bookmarked'] = false;
  2934. return $this->json($res);
  2935. }
  2936. /**
  2937. * GET /api/v2/search
  2938. *
  2939. *
  2940. * @return array
  2941. */
  2942. public function searchV2(Request $request)
  2943. {
  2944. abort_if(!$request->user(), 403);
  2945. if(config('pixelfed.bouncer.cloud_ips.ban_api')) {
  2946. abort_if(BouncerService::checkIp($request->ip()), 404);
  2947. }
  2948. $this->validate($request, [
  2949. 'q' => 'required|string|min:1|max:100',
  2950. 'account_id' => 'nullable|string',
  2951. 'max_id' => 'nullable|string',
  2952. 'min_id' => 'nullable|string',
  2953. 'type' => 'nullable|in:accounts,hashtags,statuses',
  2954. 'exclude_unreviewed' => 'nullable',
  2955. 'resolve' => 'nullable',
  2956. 'limit' => 'nullable|integer|max:40',
  2957. 'offset' => 'nullable|integer',
  2958. 'following' => 'nullable'
  2959. ]);
  2960. $mastodonMode = !$request->has('_pe');
  2961. return $this->json(SearchApiV2Service::query($request, $mastodonMode));
  2962. }
  2963. /**
  2964. * GET /api/v1/discover/posts
  2965. *
  2966. *
  2967. * @return array
  2968. */
  2969. public function discoverPosts(Request $request)
  2970. {
  2971. abort_if(!$request->user(), 403);
  2972. if(config('pixelfed.bouncer.cloud_ips.ban_api')) {
  2973. abort_if(BouncerService::checkIp($request->ip()), 404);
  2974. }
  2975. $this->validate($request, [
  2976. 'limit' => 'integer|min:1|max:40'
  2977. ]);
  2978. $limit = $request->input('limit', 40);
  2979. $pid = $request->user()->profile_id;
  2980. $filters = UserFilterService::filters($pid);
  2981. $forYou = DiscoverService::getForYou();
  2982. $posts = $forYou->take(50)->map(function($post) {
  2983. return StatusService::getMastodon($post);
  2984. })
  2985. ->filter(function($post) use($filters) {
  2986. return $post &&
  2987. isset($post['account']) &&
  2988. isset($post['account']['id']) &&
  2989. !in_array($post['account']['id'], $filters);
  2990. })
  2991. ->take(12)
  2992. ->values();
  2993. return $this->json(compact('posts'));
  2994. }
  2995. /**
  2996. * GET /api/v2/statuses/{id}/replies
  2997. *
  2998. *
  2999. * @return array
  3000. */
  3001. public function statusReplies(Request $request, $id)
  3002. {
  3003. abort_if(!$request->user(), 403);
  3004. $this->validate($request, [
  3005. 'limit' => 'int|min:1|max:10',
  3006. 'sort' => 'in:all,newest,popular'
  3007. ]);
  3008. if(config('pixelfed.bouncer.cloud_ips.ban_api')) {
  3009. abort_if(BouncerService::checkIp($request->ip()), 404);
  3010. }
  3011. $limit = $request->input('limit', 3);
  3012. $pid = $request->user()->profile_id;
  3013. $status = StatusService::getMastodon($id, false);
  3014. abort_if(!$status, 404);
  3015. if($status['visibility'] == 'private') {
  3016. if($pid != $status['account']['id']) {
  3017. abort_unless(FollowerService::follows($pid, $status['account']['id']), 404);
  3018. }
  3019. }
  3020. $sortBy = $request->input('sort', 'all');
  3021. if($sortBy == 'all' && isset($status['replies_count']) && $status['replies_count'] && $request->has('refresh_cache')) {
  3022. if(!Cache::has('status:replies:all-rc:' . $id)) {
  3023. Cache::forget('status:replies:all:' . $id);
  3024. Cache::put('status:replies:all-rc:' . $id, true, 300);
  3025. }
  3026. }
  3027. if($sortBy == 'all' && !$request->has('cursor')) {
  3028. $ids = Cache::remember('status:replies:all:' . $id, 3600, function() use($id) {
  3029. return DB::table('statuses')
  3030. ->where('in_reply_to_id', $id)
  3031. ->orderBy('id')
  3032. ->cursorPaginate(3);
  3033. });
  3034. } else {
  3035. $ids = DB::table('statuses')
  3036. ->where('in_reply_to_id', $id)
  3037. ->when($sortBy, function($q, $sortBy) {
  3038. if($sortBy === 'all') {
  3039. return $q->orderBy('id');
  3040. }
  3041. if($sortBy === 'newest') {
  3042. return $q->orderByDesc('created_at');
  3043. }
  3044. if($sortBy === 'popular') {
  3045. return $q->orderByDesc('likes_count');
  3046. }
  3047. })
  3048. ->cursorPaginate($limit);
  3049. }
  3050. $filters = UserFilterService::filters($pid);
  3051. $data = $ids->filter(function($post) use($filters) {
  3052. return !in_array($post->profile_id, $filters);
  3053. })
  3054. ->map(function($post) use($pid) {
  3055. $status = StatusService::get($post->id, false);
  3056. if(!$status || !isset($status['id'])) {
  3057. return false;
  3058. }
  3059. $status['favourited'] = LikeService::liked($pid, $post->id);
  3060. return $status;
  3061. })
  3062. ->map(function($post) {
  3063. if(isset($post['account']) && isset($post['account']['id'])) {
  3064. $account = AccountService::get($post['account']['id'], true);
  3065. $post['account'] = $account;
  3066. }
  3067. return $post;
  3068. })
  3069. ->filter(function($post) {
  3070. return $post && isset($post['id']) && isset($post['account']) && isset($post['account']['id']);
  3071. })
  3072. ->values();
  3073. $res = [
  3074. 'data' => $data,
  3075. 'next' => $ids->nextPageUrl()
  3076. ];
  3077. return $this->json($res);
  3078. }
  3079. /**
  3080. * GET /api/v2/statuses/{id}/state
  3081. *
  3082. *
  3083. * @return array
  3084. */
  3085. public function statusState(Request $request, $id)
  3086. {
  3087. abort_if(!$request->user(), 403);
  3088. if(config('pixelfed.bouncer.cloud_ips.ban_api')) {
  3089. abort_if(BouncerService::checkIp($request->ip()), 404);
  3090. }
  3091. $status = Status::findOrFail($id);
  3092. $pid = $request->user()->profile_id;
  3093. abort_if(!in_array($status->scope, ['public', 'unlisted', 'private']), 404);
  3094. return $this->json(StatusService::getState($status->id, $pid));
  3095. }
  3096. /**
  3097. * GET /api/v1.1/discover/accounts/popular
  3098. *
  3099. *
  3100. * @return array
  3101. */
  3102. public function discoverAccountsPopular(Request $request)
  3103. {
  3104. abort_if(!$request->user(), 403);
  3105. if(config('pixelfed.bouncer.cloud_ips.ban_api')) {
  3106. abort_if(BouncerService::checkIp($request->ip()), 404);
  3107. }
  3108. $pid = $request->user()->profile_id;
  3109. $ids = Cache::remember('api:v1.1:discover:accounts:popular', 86400, function() {
  3110. return DB::table('profiles')
  3111. ->where('is_private', false)
  3112. ->whereNull('status')
  3113. ->orderByDesc('profiles.followers_count')
  3114. ->limit(20)
  3115. ->get();
  3116. });
  3117. $ids = $ids->map(function($profile) {
  3118. return AccountService::get($profile->id, true);
  3119. })
  3120. ->filter(function($profile) use($pid) {
  3121. return $profile && isset($profile['id']);
  3122. })
  3123. ->filter(function($profile) use($pid) {
  3124. return $profile['id'] != $pid;
  3125. })
  3126. ->map(function($profile) {
  3127. $ids = collect(ProfileStatusService::get($profile['id'], 0, 9))
  3128. ->map(function($id) {
  3129. return StatusService::get($id, true);
  3130. })
  3131. ->filter(function($post) {
  3132. return $post && isset($post['id']);
  3133. })
  3134. ->take(3);
  3135. $profile['recent_posts'] = $ids;
  3136. return $profile;
  3137. })
  3138. ->take(6)
  3139. ->values();
  3140. return $this->json($ids);
  3141. }
  3142. /**
  3143. * GET /api/v1/preferences
  3144. *
  3145. *
  3146. * @return array
  3147. */
  3148. public function getPreferences(Request $request)
  3149. {
  3150. abort_if(!$request->user(), 403);
  3151. if(config('pixelfed.bouncer.cloud_ips.ban_api')) {
  3152. abort_if(BouncerService::checkIp($request->ip()), 404);
  3153. }
  3154. $pid = $request->user()->profile_id;
  3155. $account = AccountService::get($pid);
  3156. return $this->json([
  3157. 'posting:default:visibility' => $account['locked'] ? 'private' : 'public',
  3158. 'posting:default:sensitive' => false,
  3159. 'posting:default:language' => null,
  3160. 'reading:expand:media' => 'default',
  3161. 'reading:expand:spoilers' => false
  3162. ]);
  3163. }
  3164. /**
  3165. * GET /api/v1/trends
  3166. *
  3167. *
  3168. * @return array
  3169. */
  3170. public function getTrends(Request $request)
  3171. {
  3172. abort_if(!$request->user(), 403);
  3173. return $this->json([]);
  3174. }
  3175. /**
  3176. * GET /api/v1/announcements
  3177. *
  3178. *
  3179. * @return array
  3180. */
  3181. public function getAnnouncements(Request $request)
  3182. {
  3183. abort_if(!$request->user(), 403);
  3184. return $this->json([]);
  3185. }
  3186. /**
  3187. * GET /api/v1/markers
  3188. *
  3189. *
  3190. * @return array
  3191. */
  3192. public function getMarkers(Request $request)
  3193. {
  3194. abort_if(!$request->user(), 403);
  3195. if(config('pixelfed.bouncer.cloud_ips.ban_api')) {
  3196. abort_if(BouncerService::checkIp($request->ip()), 404);
  3197. }
  3198. $type = $request->input('timeline');
  3199. if(is_array($type)) {
  3200. $type = $type[0];
  3201. }
  3202. if(!$type || !in_array($type, ['home', 'notifications'])) {
  3203. return $this->json([]);
  3204. }
  3205. $pid = $request->user()->profile_id;
  3206. return $this->json(MarkerService::get($pid, $type));
  3207. }
  3208. /**
  3209. * POST /api/v1/markers
  3210. *
  3211. *
  3212. * @return array
  3213. */
  3214. public function setMarkers(Request $request)
  3215. {
  3216. abort_if(!$request->user(), 403);
  3217. if(config('pixelfed.bouncer.cloud_ips.ban_api')) {
  3218. abort_if(BouncerService::checkIp($request->ip()), 404);
  3219. }
  3220. $pid = $request->user()->profile_id;
  3221. $home = $request->input('home.last_read_id');
  3222. $notifications = $request->input('notifications.last_read_id');
  3223. if($home) {
  3224. return $this->json(MarkerService::set($pid, 'home', $home));
  3225. }
  3226. if($notifications) {
  3227. return $this->json(MarkerService::set($pid, 'notifications', $notifications));
  3228. }
  3229. return $this->json([]);
  3230. }
  3231. }