ApiV1Controller.php 141 KB

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