1
0

ApiV1Controller.php 99 KB

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