ApiV1Controller.php 126 KB

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