1
0

ApiV1Controller.php 140 KB

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