ApiV1Controller.php 103 KB

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