ApiV1Controller.php 135 KB

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