ApiV1Controller.php 95 KB

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