ApiV1Controller.php 125 KB

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