ApiV1Controller.php 103 KB

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