ApiV1Controller.php 129 KB

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