ApiV1Controller.php 84 KB

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