ApiV1Controller.php 103 KB

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